我有一本字典:排序一本詞典值(名單)賦予功能給它
students = {
'1': [32, 14, 31, 23],
'2': [32, 8, 36.5, 22],
'3': [26, 11, 39, 15.5],
'4': [34, 15, 44, 25],
'5': [30, 6, 25, 24],
'6': [26, 8, 31, 13],
'7': [24, 4, 16, 17],
'8': [22, 2, 0, 11.2],
'9': [22, 4, 15, 10],
'10': [31, 4, 16, 4.2],
'11': [18, 3.5, 0, 0],
'12': [28, 5, 30, 18.5],
'13': [34, 13, 23, 13],
}
我想每個列表的總和排序的字典。所以,我能做到這一點是這樣的:
import operator
students = {
'1': sum([32, 14, 31, 23]),
'2': sum([32, 8, 36.5, 22]),
'3': sum([26, 11, 39, 15.5]),
'4': sum([34, 15, 44, 25]),
'5': sum([30, 6, 25, 24]),
'6': sum([26, 8, 31, 13]),
'7': sum([24, 4, 16, 17]),
'8': sum([22, 2, 0, 11.2]),
'9': sum([22, 4, 15, 10]),
'10': sum([31, 4, 16, 4.2]),
'11': sum([18, 3.5, 0, 0]),
'12': sum([28, 5, 30, 18.5]),
'13': sum([34, 13, 23, 13]),
}
sorted_students = sorted(
students.items(), key=operator.itemgetter(1), reverse=True)
但是:
- 我不想改變字典,我想有列爲值
- 我不想寫
sum()
這麼多次。
我試圖key=sum(operator.itemgetter(1))
但很顯然,這是行不通的,我得到:
TypeError: 'operator.itemgetter' object is not iterable
什麼是更有效的方式做我想做什麼?