2012-05-27 25 views
3

我有三個數字值(重量,計數,貢獻)的各種字符串(單詞),我想組織成一個多維數組,然後排序。要做到這一點,我的字典,其中的數值是在列表中,字符串是關鍵中所做的列表:用於在Python中對多維數組進行排序的適當數據結構?

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

列表_are_在python中排序。我認爲你的意思是「字典無序」。 –

+0

謝謝,我編輯了這個帖子來澄清。 – Zach

+0

此外,你不能像這樣的字典上使用itemgetter。你必須調用'print_dictionary.items()'。 –

回答

4

你可以傳遞一個匿名函數爲重點,以sorted。這使用了多維字典作爲密鑰的第三構件:

>>> 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] 

More about sorted and sorting in Python

+1

關閉時,只需將slice語句放在sorted上:'sorted(d,key = lambda x:d [x] [2])[:10]' – Devourant

+0

完美,謝謝! – Zach

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]) 
+1

@zach:見上面編輯的答案。 –

相關問題