首页 > 解决方案 > 在 Python 列表中查找“x”最大差异

问题描述

假设我有一个数据列表......例如股票价格,我想了解更多关于列表中每个元素之间的差异 - 特别是最大的差异。在这种情况下,它将找到表现出最大变化(即最大收益或损失)的 2 个价格。

现在,我不只是想找到唯一的最大差异。我想找到可能最大的 5 个差异 - 其中用于计算差异的所有 5 对数字都是唯一的,并且不会收敛于相同的解决方案。

可以做到这一点的一种方法是使用嵌套的 for 循环,如下所示:

nums = [1,2,3,4,5]

for i in nums:
    for x in nums:
        return x-i

但我觉得这种方法真的很笨拙,并没有解决手头的问题。有一个更好的方法吗?谢谢!

编辑:

感兴趣的人的解决方案

我使用@Chris_Rands 答案的修改版本来解决问题。基本上,这个函数只是找到一个最大的差异,然后从原始列表中删除每个元素并执行此过程,直到只剩下 1 个元素(当你找不到另一个差异时)。结果是一个元组数组,其中包含与数据集最大差异的 100% 唯一对:

from itertools import combinations
from heapq import nlargest

nums = [98,34,513,352,3523,308,13]

def findTrades(list_, amount):
    Trades_ = []

    while len(list_) >= 2:
        res = nlargest(1, combinations(list_, 2), key = lambda x: abs(x[0]-x[1]))
        Trades_.append(res)
        for i in res[0]:
            list_ = [x for x in list_ if x != i]

    return sorted(Trades_)[-amount:]

print (findTrades(nums, 3))

标签: pythonpython-3.xlistfor-loopdifference

解决方案


在这里x=3。使用heapq.nlargest比对 的小值进行排序要好x

>>> from itertools import combinations
>>> from heapq import nlargest
>>> nlargest(3, combinations(nums, 2), key = lambda x: abs(x[0]-x[1]))
[(1, 5), (1, 4), (2, 5)]

推荐阅读