【问题标题】:Python - find integer closest to 0 in list [duplicate]Python - 在列表中找到最接近0的整数[重复]
【发布时间】:2012-08-09 01:17:39
【问题描述】:

可能重复:
finding index of an item closest to the value in a list that's not entirely sorted

我有一个 Python 中的正数和负数列表 ([237, 72, -18, 237, 236, 237, 60, -158, -273, -78, 492, 243])。我想找到最接近 0 的数字。我该怎么做?

【问题讨论】:

标签: python algorithm list numbers


【解决方案1】:

这个怎么样:

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)

【讨论】:

  • 如果负数和正数最接近 0,将始终返回负数。
【解决方案2】:
reduce(lambda x, y : x if abs(y) > abs(x) else y, your_sequence)

【讨论】:

    猜你喜欢
    • 2015-07-26
    • 2017-12-06
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 2015-08-03
    • 2020-09-01
    相关资源
    最近更新 更多