Python 如何修复返回错误值的.index()方法?

Python 如何修复返回错误值的.index()方法?,python,list,Python,List,我试图从以下列表中获取大于70的值的索引: 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 in temperatures: if i > 70: hour_ex.append(temperatures.inde

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

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 in temperatures:
    if i > 70:
        hour_ex.append(temperatures.index(i))

print(hour_ex)
上面的代码正在打印:

[9, 10, 10, 13, 15]
当循环到达索引12时,它再次打印索引10,因为它具有相同的值。我不知道发生了什么事。如何修复它?

来自for
列表。索引(x[,start[,end]])

返回值等于x的第一个项列表中从零开始的索引。如果没有此类项,则引发ValueError

要实现您的目标,您可以执行以下操作:

hour_ex=[i代表i,n在枚举(温度)中,如果n>70]

您可以在循环中使用范围:

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 in range(len(temperatures)):
    if temperatures[i] > 70:
        hour_ex.append(i)

print(hour_ex)

索引
是一种列表搜索功能,它在列表中执行线性遍历以查找给定元素的第一个位置。这就解释了您令人困惑的输出——在重复的情况下,例如80,
index()
将始终为该元素提供它能找到的第一个索引,即10

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

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

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]
考虑使用列表理解,它对枚举列表执行过滤操作:

hour_ex = [i for i, temp in enumerate(temperatures) if temp > 70]
所以,如果列表
索引中有重复的值,则
将返回值的最小索引

你可以试试

hour_ex=[]
对于idx,枚举中的回火(温度):
如果回火>70:
小时附加(idx)
打印(小时)

OP要求的是索引列表,而不是值列表。谢谢ggorlen。现在我正确地了解了.index()行为以及为什么要使用enumerate。谢谢!
In simple terms, index() method finds the given element in a list and returns its position.

However, if the same element is present more than once, index() method returns its smallest/first position.