简体   繁体   English

使用 .index() 查找最小元素会产生意想不到的结果

[英]Finding min element using .index() gives unexpected result

I don't understand what is wrong in this list我不明白这个列表有什么问题

L = [20,5,4,85,96,75,3,3.1]
m = min(i for i in L if L.index(i)%2==1)

print L.index(m), m

the output as I expected:输出如我所料:

7 3.1

but when I change the last number in list 3.1 to 3但是当我将列表 3.1 中的最后一个数字更改为 3 时

L = [20,5,4,85,96,75,3,3]
m = min(i for i in L if L.index(i)%2==1)

print L.index(m), m

the output was not 3:输出不是 3:

1 5

please explain the reason请解释原因

You can use enumerate() , to get position for each value in the list:您可以使用enumerate()来获取列表中每个值的位置:

L = [20,5,4,85,96,75,3,3]
m = min(j for (i,j) in enumerate(L) if i%2==1)

Output:输出:

6 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM