python - 在 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))
解决方案
在这里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)]
推荐阅读
- ruby-on-rails - Rails Active Admin 在显示页面上更新用户状态
- java - 从 jar 中的资源运行 SH 文件
- go - 使用没有 -linkshared 构建的二进制文件时不打印二进制地址
- python - 使用 SparkTrials 的 hyperopt 并行化
- laravel-livewire - laravel wire : 通过在 livewire 中传递具有相同组件的不同参数来调用两个不同的路由
- flutter - Flutter:MissingPluginException(在通道 plugins.flutter.io/firebase_core 上找不到方法 Firebase#initializeCore 的实现)
- c# - 如何在 WinForms 中使用来自服务器的外部配置文件?
- ejs - 在我的编码课程中使用 EJS 时出现编译器错误
- html - 强制图像调整大小以适合 div
- assembly - 为什么汇编中字符串变量的末尾包含 0?