问题
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)
The code above is printing:
[9, 10, 10, 13, 15]
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?
回答1:
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.
Use enumerate()
if you're interested in obtaining the indices as a tuple for each element of the list.
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]
回答2:
From the python docs for list.index(x[, start[, end]])
:
Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.
To achieve what you are trying to do, you could do the following:
hour_ex = [i for i, n in enumerate(temperatures) if n > 70]
回答3:
You can use range in the loop:
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)
回答4:
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.
So, if has duplicate value in list index
will return smallest index of value
You can try
hour_ex = []
for idx, temper in enumerate(temperatures):
if temper > 70:
hour_ex.append(idx)
print(hour_ex)
来源:https://stackoverflow.com/questions/56712035/how-to-fix-index-method-returning-the-wrong-value