我需要从这个列表的最小元素中获取所有索引:
A = [5,2,1,5,6,1,7,9,2]
minimo = min(A)
#print minimo
indexArray = []
for elem in A:
#print elem
if elem == minimo:
indexArray.append(A.index(elem))
print indexArray
需要此输出:[2,5] 但它打印出来:[2,2]
答案 0 :(得分:2)
您可以list-comprehension
使用enumerate()
。感谢@MikeScotty
,性能改进将首先计算最小值。
以下是代码:
mn = min(A)
[i for i,e in enumerate(A) if e == mn]
给出:
[2, 5]
这是1s
中A
的索引 - 而不是[2, 8]
为了证明这一点更快,请minx
wrapper
:
>>> def minx(l):
... print("called")
... return min(l)
...
>>> [i for i,e in enumerate(A) if e == minx(A)]
called
called
called
called
called
called
called
called
called
[2, 5]
使用timeit
的一些时间安排:
>>> timeit.timeit("[i for i,e in enumerate(A) if e == min(A)]", globals=locals())
5.9568054789997404
>>> timeit.timeit("[i for i,e in enumerate(A) if e == 1]", globals=locals())
1.397674421001284
答案 1 :(得分:0)
你也可以尝试这个:
A = [5,2,1,5,6,1,7,9,2]
minimum = min(A)
res = list(filter(lambda m: A[m]==minimum, range(len(A))))
print(res)
输出结果为:
[2, 5]
答案 2 :(得分:0)
因为当你使用
A.index(elem)
它与A.index(1)相同,索引1将始终为2.您可以尝试这个脚本:
A=[5,2,1,5,6,1,7,9,2]
minimo = min(A)
indexArray = []
for index,value in enumerate(A):
if value == minimo:
indexArray.append(index)
print(indexArray)