将给定的数组 A(10) 中最大值和最小值之间的所有元素替换为数字 100。

huangapple go评论59阅读模式
英文:

The array A(10) is given. Replace all the elements standing between the largest and the smallest with the number 100

问题

我有一个关于Python任务的问题
例如:
数组 [1, 5, 2, 3, -1, 3]
新数组 [1, 5, 100, 100, -1, 3]

我不知道如何做这个,因为我是Python新手。

英文:

I have a problem with python task
for example:
array [1, 5, 2, 3, -1, 3]
new_array [1, 5, 100, 100, -1, 3]

i dont know how do this cuz i new in python

答案1

得分: 0

你可以找到最小和最大值的索引,然后将对应的列表替换为100:

A = [1, 5, 2, 3, -1, 3]

start, end = sorted(map(A.index, (min(A), max(A)))
A[start+1:end] = [100] * len(A[start+1:end])

print(A) # [1, 5, 100, 100, -1, 3]

如果你需要它在一个单独的变量中,你可以事先复制(例如:new_array = array.copy())并在复制上操作

英文:

You could find the indexes of the minimum and maximum values and then assign a corresponding list of 100s to the subscript:

A = [1, 5, 2, 3, -1, 3]

start,end = sorted(map(A.index,(min(A),max(A))))
A[start+1:end] = [100]*len(A[start+1:end])

print(A) # [1, 5, 100, 100, -1, 3]

If you need it to be in a separate variable you can make copy beforehand (ex: new_array = array.copy()) and work on the copy

答案2

得分: -1

我的解决方案仅适用于在最小值之前出现最大值的情况,但您可以轻松更新这个解决方案。

array = [1, 5, 2, 3, -1, 3]
c = []
for i, j in enumerate(array):
    if i <= array.index(max(array)) or i >= array.index(min(array)):
        c.append(j)
    else:
        c.append(100)
print(c)
英文:

my solution works only for this case when maximal value before minimal but you could easily update this solution.

array = [1, 5, 2, 3, -1, 3] 
c = []
for i,j in enumerate(array):
if i&lt;=(array.index(max(array))) or i&gt;=array.index(min(array)):
    c.append(j)
else:
    c.append(100)

print(c)

huangapple
  • 本文由 发表于 2023年2月18日 02:44:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75488196.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定