如何修复.index()方法返回错误的值? [英] How to fix .index() method returning the wrong value?

查看:68
本文介绍了如何修复.index()方法返回错误的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从以下列表中获取大于70的值的索引:

I'm trying to get the index of the values higher than 70 from the following list:

temperatures = [33, 66, 65, 62, 59, 60, 62, 64, 70, 76, 80, 69, 80, 83, 68, 79, 61, 53, 50, 49, 53, 48, 45, 39]

但是当循环找到相等的值时出了点问题:

But something is going wrong when the loop finds equal values:

hour_ex = []
for i in temperatures:
    if i > 70:
        hour_ex.append(temperatures.index(i))

print(hour_ex)

上面的代码正在打印:

[9, 10, 10, 13, 15]

当循环到达索引12时,因为它具有相同的值,所以它再次打印索引10.我不知道这是怎么回事.我该如何解决?

When the loop reach the index 12, it prints again the index 10 because it has the same value. I don't know what's going on. How can I fix it?

推荐答案

index 是一个列表搜索功能,可对列表进行线性遍历以查找给定元素的第一个位置.这就解释了您令人困惑的输出-如果重复项如80,则 index()将始终为您找到该元素的第一个索引,即10.

index is a list-searching function that performs a linear walk through the list to find the first position of a given element. This explains your confusing output--in the case of duplicates like 80, index() will always give you the first index it can find for that element, which is 10.

如果您有兴趣获取列表中每个元素的元组索引,请使用 enumerate().

Use enumerate() if you're interested in obtaining the indices as a tuple for each element of the list.

此外,变量 i 表示索引,但实际上表示列表中的给定温度;这是一个误导性的变量名.

Additionally, the variable i suggests index, but actually represents a given temperature in the list; it's a misleading variable name.

temperatures = [33, 66, 65, 62, 59, 60, 62, 64, 70, 76, 80, 69, 80, 83, 68, 79, 61, 53, 50, 49, 53, 48, 45, 39]    
hour_ex = []

for i, temperature in enumerate(temperatures):
    if temperature > 70:
        hour_ex.append(i)

print(hour_ex) # => [9, 10, 12, 13, 15]

请考虑使用列表理解功能,该功能对枚举列表执行过滤操作:

Consider using a list comprehension, which performs a filtering operation on the enumerated list:

hour_ex = [i for i, temp in enumerate(temperatures) if temp > 70]

这篇关于如何修复.index()方法返回错误的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆