我有一个元组列表,其格式如下(“key”,“value”),我需要提取最高和最高的键。第二高的价值和存储它们,我如何在python中实现这一点?
答案 0 :(得分:2)
import heapq
heapq.nlargest(2, list_of_t, key=lambda x:x[1])
<强>演示:强>
>>> import heapq
>>> list_of_t = [('a', 100), ('b', 5), ('c', 50)]
>>> heapq.nlargest(2, list_of_t, key=lambda x:x[1])
[('a', 100), ('c', 50)]
答案 1 :(得分:0)
试试这个:
# initial data
tuples = [("First", 20), ("Second", 10), ("Third", 30)]
# sort by value and reverse it
sorted_tuples = sorted(tuples, key=lambda tuple: tuple[1])[::-1]
# show result
print(sorted_tuples[0])
print(sorted_tuples[1])
# results:
#
# ('Third', 30)
# ('First', 20)