Python 在已排序的字典中为每个键作为元组的子键获取顶部项
我有一个字典,其中key和value都是元组,其中key是(queryID,句子),value是(score,documentID)(在key和value元组中,第一项是数字,第二项是字符串) 我已经按照查询ID对这个dict进行了分组,并按照分数进行了排序,因此对于每个查询ID,我都按照分数对项目进行了排序 我想做的是,对于每个查询ID,获取已经排序的dict中的前k项。 因此,如果查询ID=1有100个条目,而qID=2也有100个条目,那么我希望为每个条目获取排序后的dict中的前k个条目。 请问怎么做 这是我的代码的一部分,用于获取已排序的dict-Python 在已排序的字典中为每个键作为元组的子键获取顶部项,python,python-2.7,dictionary,information-retrieval,Python,Python 2.7,Dictionary,Information Retrieval,我有一个字典,其中key和value都是元组,其中key是(queryID,句子),value是(score,documentID)(在key和value元组中,第一项是数字,第二项是字符串) 我已经按照查询ID对这个dict进行了分组,并按照分数进行了排序,因此对于每个查询ID,我都按照分数对项目进行了排序 我想做的是,对于每个查询ID,获取已经排序的dict中的前k项。 因此,如果查询ID=1有100个条目,而qID=2也有100个条目,那么我希望为每个条目获取排序后的dict中的前k个条目
sorted_dict=collections.OrderedDict(sorted(sen_dict.items(), key= lambda x: (-int(x[0][0]),x[1][0]),reverse=True)
您可以在字典中循环并附加一个结果数组。如果qID线性增加1,我想类似的方法应该会起作用:
results=[]
i = 1
for key in d:
if key[0]==i:
currentResult=d[key]
else:
results.append(currentResult)
currentScore=0
i+=1
results.append(currentResult)
这只适用于总是只有一个项目的最高分数,但它可以很容易地附加到工作的多个项目相同的分数
results=[]
i = 1
currentResults=[]
currentScore = 0
for key in d:
if key[0]==i:
if currentScore == d[key][0]:
currentResults.append(d[key])
elif currentScore < d[key][0]:
currentResults = [d[key]]
currentScore = d[key][0]
else:
results.append(currentResult)
i+=1
results.append(currentResult)
results=[]
i=1
currentResults=[]
currentScore=0
对于输入d:
如果键[0]==i:
如果currentScore==d[键][0]:
currentResults.append(d[键])
elif currentScore
我想这样应该行。这使用排序的dict变量来获得与每个查询ID相关的前K个最高分数
k = 2 #assign how many top values you want to see
id = 1 #assign queryID
topK = [val for key,val in sorted_dict.items() if key[0] == id][0:k]
print topK
分类词典?你能展示一下你的代码吗?谢谢,我正在寻找一个简短的解决方案。
k = 2 #assign how many top values you want to see
id = 1 #assign queryID
topK = [val for key,val in sorted_dict.items() if key[0] == id][0:k]
print topK