【问题标题】:How to get 5 closest integers out of python list? [duplicate]如何从 python 列表中获取 5 个最接近的整数? [复制]
【发布时间】:2020-04-25 08:01:38
【问题描述】:

我想得到最接近100的5个整数,比如100, 99,98, 101, 102 我使用了以下方法,但都没有得到想要的结果。

myList = [95,96,97,98,99,100,101,102,103,104,105]
for i in myList:
    print(min(myList, key=lambda x:abs(x-100)))
    myList.remove(i)

输出:

100
100
100
100
100
100

然后我这样做了:

myList = [95,96,97,98,99,100,101,102,103,104,105]
for i in myList:
    print(min(myList, key=lambda x:abs(x-i)))
    myList.remove(i)

输出:

95
97
99
101
103
105

在这种情况下,超过 95、97 和 105; 98、96 和 102 最接近;而是跳过这些关闭数字。

请看一下并提出建议。 谢谢:)

【问题讨论】:

    标签: python list algorithm sorting closest


    【解决方案1】:

    您只是打印最小值(相对于您的定义),但随后您只是弹出下一个元素。相反,请执行以下操作:

    myList = [95,96,97,98,99,100,101,102,103,104,105]
    for i in range(5):  # we want 5 elements
        best = min(myList, key=lambda x: abs(100-x))
        myList.remove(best)
        print(best)
    

    打印出来的:

    100
    99
    101
    98
    102
    

    但是有一种更简单的方法可以得到你想要的。只需对其进行排序并取前 n 个元素:

    # prints [100, 99, 101, 98, 102]
    print(sorted(myList, key=lambda x: abs(100-x))[:5])
    

    The top answer to the duplicate question 有一个更好的 (?(n)) 解决方案:

    from heapq import nsmallest
    print(nsmallest(5, myList, key=lambda x: abs(100-x))
    

    【讨论】:

      猜你喜欢
      • 2021-05-11
      • 2012-08-21
      • 2019-03-25
      • 2016-08-04
      • 2016-06-24
      • 2022-01-16
      • 2012-08-09
      相关资源
      最近更新 更多