问题
Possible Duplicate:
finding index of an item closest to the value in a list that's not entirely sorted
I've got a list of positive and negative numbers in Python ([237, 72, -18, 237, 236, 237, 60, -158, -273, -78, 492, 243]
). I want to find the number which is closest to 0. How do I do this?
回答1:
How about this:
lst = [237, 72, -18, 237, 236, 237, 60, -158, -273, -78, 492, 243]
min((abs(x), x) for x in lst)[1]
A nice and much shorter answer:
min(lst, key=abs)
回答2:
reduce(lambda x, y : x if abs(y) > abs(x) else y, your_sequence)
来源:https://stackoverflow.com/questions/11923657/python-find-integer-closest-to-0-in-list