2012-08-12 290 views
4

可能重複:
finding index of an item closest to the value in a list that's not entirely sorted的Python - 找到最接近的整數爲0,在列表

我得在Python([237, 72, -18, 237, 236, 237, 60, -158, -273, -78, 492, 243])正數和負數的列表。我想找到最接近0的數字。我該怎麼做?

+0

http://stackoverflow.com/questions/9706041/finding-index-of-an -item-nearest-the-value-in-a-list-thats-not-entire-sort看起來像是同一個問題被問及並回答。 – Tim 2012-08-12 16:12:51

回答

29

如何:

lst = [237, 72, -18, 237, 236, 237, 60, -158, -273, -78, 492, 243] 
min((abs(x), x) for x in lst)[1] 

一個很好的和更短的答案:

min(lst, key=abs) 
1
reduce(lambda x, y : x if abs(y) > abs(x) else y, your_sequence) 
相關問題