我有三个数字值(权重,计数,贡献),我想组织成一个多维数组,然后排序各种字符串(单词)。为此,我在字典中创建了列表,其中数值在列表中,字符串是键:
print_dictionary[word] = [weight,count,contribution]
如何按升序排序,然后按降序排序,按'贡献'(列表中的第三个值)排序,并显示排序列表的前10项。我怎么能这样做?
例如,对于以下print_dictionary:
print_dictionary[sam] = [2,7,1]
print_dictionary[sun] = [4,1,3]
print_dictionary[dog] = [1,3,2]
我希望他们能够按升序排列贡献:
Word: Weight: Count: Contribution:
sam 2 7 1
dog 1 3 2
sun 4 1 3
我不知道如何使用itemegetter:
sorted(print_dictionary, key=itemgetter(2))
答案 0 :(得分:4)
您可以将匿名函数作为sorted
的密钥传递。这使用多维dict的第三个成员作为关键:
>>> d = {'a': [1, 4, 7], 'b': [2, 3, 9], 'c': [3, 2, 8]}
>>> for key in sorted(d, key=lambda x: d[x][2]):
... print key, d[key]
a [1, 4, 7]
c [3, 2, 8]
b [2, 3, 9]
对于降序,请使用reverse=True
。要限制结果,请添加[:N]
:
sorted(d, key=lambda x: d[x][2], reverse=True)[:2]
# b [2, 3, 9]
# c [3, 2, 8]
答案 1 :(得分:1)
你无法对字典进行排序;当你尝试时,你真的只是从字典中排序键列表。您可以使用自定义排序比较来查看值中的第三项。
sorted(print_dictionary, key=lambda word: print_dictionary[word][2])
为了生成你的报告,这样的事情会起作用:
sorted_keys = sorted(print_dictionary, key=lambda word: print_dictionary[word][2])
print "Word:\tWeight:\tCount:\tContribution"
for i in range(10): # or however many you want
word = sorted_keys[i]
values = print_dictionary[word]
print "\t".join([word]+[str(n) for n in values])