2012-08-12 339 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) 
相关问题