字典中具有最高值的前n个键,以元组作为键

问题描述:

我想用字母组作为键来获取字典的前n个键,其中元组的第一个值是特定数字(下面的示例中为1):

I want to get the top n keys of a dictionary with tuples as keys, where the first value of the tuple is a particular number (1 in the example below):

a = {}
a[1,2] = 3
a[1,0] =4
a[1,5] = 1
a[2,3] = 9

我想[1,0]和[1, 2]返回,其中元组/ key = 1的第一个元素= 1

I want [1,0] and [1,2] to be returned, where the first element of the tuple/key = 1

import heapq
k = heapq.nlargest(2, a, key=a.get(1,))

返回[1,4]和[1,3],第一个元素= 1的最高键/元组,但如果我使用

returns [1,4] and [1,3], the highest keys/tuples with first element = 1, though if I make it

k = heapq.nlargest(2, a, key=a.get(2,))

它返回相同的东西?

首先你应该只具有第一坐标的键1.否则,如果存在具有1作为第一坐标的几个元素,则还有其他元组。然后可以正常使用 heapq 。例如:

First you should take only the keys with first coordinate 1. Otherwise, there is the chance if there are a few elements with 1 as first coordinate, to get other tuples also. Then you can use heapq normally. For example:

a = {
    (1, 2): 3,
    (1, 0): 4,
    (1, 5): 1,
    (2, 3): 9
}

import heapq
print heapq.nlargest(2, (k for k in a if k[0] == 1), key=lambda k: a[k])
print heapq.nlargest(2, (k for k in a if k[0] == 2), key=lambda k: a[k])

输出:

[(1, 0), (1, 2)]
[(2, 3)]