[英]Python sort Value list, then sort by value
I have a dictionary, with a name as a key and a list containing scores as the value. 我有一本字典,一个名字作为键,一个包含分数作为值的列表。
I'm trying to sort the lists in the values and then sort the whole dictionary by the values - making it so it's sorted by the highest score. 我正在尝试按值对列表进行排序,然后按值对整个字典进行排序-使其按最高分数排序。
Here's the dictionary: 这是字典:
{'Dave_Wright': [10], 'Clara_Johnson': [9, 7], 'Amy_Kukri': [9, 8, 9], 'Eden_Jia': [10]}
I'm trying to use code I'v found from other places of stackoverflow, but I've not found a question specific to this yet. 我正在尝试使用从stackoverflow的其他地方找到的代码,但是我还没有找到特定于此的问题。
print(d2)
d2 = sorted(d2.items(), key = itemgetter(1))
for key in d2:
print(key, d2[key])
I'm probably making a mountain out of a molehill with this, but I am genuinely stumped. 我可能用这种方法在一座小山上开了一座山,但是我真的很沮丧。
Just itemgetter(1)
will not do the sorting. 仅
itemgetter(1)
不会进行排序。 You need to write your own key for this: 您需要为此编写自己的密钥:
def get_return(key_value):
return list(sorted(key_value[1])), key_value[0]
d2 = sorted(d2.items(), key=get_return, reverse=True)
for key, value in d2:
print(key, value)
Here is a helpful tutorial for sorting dictionaries by keys/values that was recommended by spectre-d 这是Spectre-d建议的按键/值对字典排序的有用教程
This will print the dictionary in the order you've specified (assuming that you meant highest-score first): 这将按照您指定的顺序打印字典(假设您首先意味着最高分数):
d = {'Dave_Wright': [10], 'Clara_Johnson': [9, 7], 'Amy_Kukri': [9, 8, 9], 'Eden_Jia': [10]}
print ('\n'.join(
'{}, {}'.format(key, sorted(value, reverse=True))
for key, value in sorted(d.items(), key=lambda x:x[1], reverse=True)))
Result: 结果:
Dave_Wright, [10]
Eden_Jia, [10]
Amy_Kukri, [9, 9, 8]
Clara_Johnson, [9, 7]
Dictionaries aren't usually sortable; 字典通常不是可排序的; though you can sort the key-value pairs in the dictionary.
尽管您可以在字典中对键/值对进行排序。
for name, scores in sorted(d2.items(), key=lambda x: max(x[1]), reverse=True):
print name, sorted(scores) # reverse=True?
for l in d.values():
l.sort(reverse=True) # this will sort the values in place(mutate the dict)
result = sorted(d.items(), key=lambda x: x[1], reverse=True)
Out[518]:
[('Eden_Jia', [10]),
('Dave_Wright', [10]),
('Amy_Kukri', [9, 9, 8]),
('Clara_Johnson', [9, 7])]
Is this the output you expected? 这是您期望的输出吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.