如何从大元组列表中获得最好的两个元组

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-77129-95给出了最大的范围。我怎样才能在 Python 中做到这一点?

Mur*_*nik 6

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)