基于python中的值提取元组

时间:2014-03-13 09:53:25

标签: python list tuples

我有一个元组列表,其格式如下(“key”,“value”),我需要提取最高和最高的键。第二高的价值和存储它们,我如何在python中实现这一点?

2 个答案:

答案 0 :(得分:2)

使用heaq.nlargest

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)