python - 从Python列表中获取索引

标签 python list min

我需要从此列表的最小元素中获取所有索引:

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]

最佳答案

您可以将列表理解enumerate()结合使用。感谢 @MikeScotty,性能改进将是首先计算最小值。

代码如下:

mn = min(A)
[i for i,e in enumerate(A) if e == mn]

给出:

[2, 5]

这是 A1 的索引 - 不是 [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

关于python - 从Python列表中获取索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47365785/

相关文章:

c++ - C++中结构数组元素的最小值和索引

python - 使用 PyCharm 调试扭曲的应用程序

python - 从 python 范围生成的列表中删除元素?

list - Groovy groupby 从 Map 值生成的列表

c# - 具有完全相同的键和值的字典

Python:对于列表中的每个元组,检查字符串是否在元组中

mysql - 所有行中重复的列的最小值和最大值

python - 正则表达式用于加号和减号以及字母?

python - scipy.integrate 的意外行为

python - 查找函数的最小值和最大值