Mas*_*s17 1 python tuples list top-n python-3.x
我有一个包含很多元组的 Python 列表。我想找到最好的两个元组,以便其中具有最好的两个最大范围值。
list_ = [(55, 55), (77, 81), (95, 129)]
Run Code Online (Sandbox Code Playgroud)
所以在这个例子中,我应该能够恢复(77, 81), (95, 129). 因为81-77和129-95给出了最大的范围。我怎样才能在 Python 中做到这一点?
heapq.nlargest 使用自定义键应该可以解决问题:
from heapq import nlargest
list_ = [(55, 55), (77, 81), (95, 129)]
result = nlargest(2, list_, key = lambda x: x[1] - x[0])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |