Python - find integer closest to 0 in list [duplicate]

↘锁芯ラ 提交于 2020-01-01 09:23:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!