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
129 views
in Technique[技术] by (71.8m points)

python - When there are two identical smallest values in a list, how do you get the first value instead of the second?

I have to get the smallest value from a list of monthly precipitation stats, then find the index of that element, then get the element with the same index value from a dictionary. This is the part of the code that is supposed to do this:

# finds the minimum precipitation from user's inputs and finds the corresponding month
min_precipitation = min(precipitation_by_month)
lowest_precipitation = precipitation_by_month.index(min_precipitation)
lowest_precipitation_month = months.pop(lowest_precipitation)
print (lowest_precipitation_month, 'has the lowest precipitation:', "{:.2f}".format(min_precipitation), 'inches.')

The problem is that in one of the inputs for this HW there are two 0.00 values in the list, but the program gets the second 0.00 value instead of the first (which is required) and therefore the wrong index number too.

Am I doing something wrong? How can I fix this?

question from:https://stackoverflow.com/questions/66054874/when-there-are-two-identical-smallest-values-in-a-list-how-do-you-get-the-first

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

1 Reply

0 votes
by (71.8m points)

Just use the list.index method with the min(list) method and you will get index of the first smallest number in the list:

n = [0,1,2,3,0]

print(n.index(min(n)))

Output:

Index is: 0

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

...