Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

python - How to fix .index() method returning the wrong value?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...