简体   繁体   English

Python:按键的一部分对字典中的项目排序?

[英]Python: sorting items in a dictionary by a part of a key?

Say I have a dictionary of kings with roman numerals in their names as the key, the roman numerals in integer form as the values. 假设我有一个国王字典,名称中的罗马数字为键,罗马数字为整数。

d = {'Zemco III': 3, 'Usamec XL': 40, 'Usamec VII': 7, 'Robert VIII': 8, 'Usamec XLII': 42, 'Mary XXIV': 24, 'Robert III': 3, 'Robert XV': 15, 'Usamec XLIX': 49}

I would like to sort the list from oldest to youngest, that is Usamec XLII should come before Usamec XLIX. 我想按从大到小的顺序排序,那就是Usamec XLII应该排在Usamec XLIX之前。 I would also like to sort the list alphabetically, that is the Usamec XLII should come before Zemco III. 我也想按字母顺序对列表进行排序,那就是Usamec XLII应该排在Zemco III之前。

My approach was to sort by name first, then by roman numeral value as such: 我的方法是先按名称排序,然后按罗马数字值排序:

x = sorted(d.items(),key=operator.itemgetter(0))
y = sorted(x,key=operator.itemgetter(1))

However, because the roman numerals are part of the key, my alphabetical sort does not work as intended. 但是,由于罗马数字是键的一部分,因此我的字母排序无法按预期工作。 My question is, can I sort the dictionary by a part of the key, for example if my key is Zemco III, can I sort my items somehow with key.split()[0] instead of the entire key? 我的问题是,我可以按键的一部分对字典进行排序吗,例如,如果我的键是Zemco III,是否可以使用key.split()[0]而不是整个键对项进行排序? Thanks! 谢谢!

key is just a function that receives an item and returns what you need to sort on. key只是一个接收项目并返回需要排序的函数。 It can be anything. 可以是任何东西。

This sorts the items by the (name_without_rightmost_word, number) key: 这通过(name_without_rightmost_word, number)键对项目进行排序:

In [92]: sorted(d.items(), key=lambda (name, num): (name.rsplit(None, 1)[0], num))
Out[92]:
[('Mary XXIV', 24),
 ('Robert III', 3),
 ('Robert VIII', 8),
 ('Robert XV', 15),
 ('Usamec VII', 7),
 ('Usamec XL', 40),
 ('Usamec XLII', 42),
 ('Usamec XLIX', 49),
 ('Zemco III', 3)]

If you use python 3, use this key : 如果您使用python 3,请使用以下key

lambda item: (item[0].rsplit(None, 1)[0], item[1])

key.rsplit(None, 1)[0] is better than key.split()[0] in case of multiword names. key.rsplit(None, 1)[0]优于key.split()[0]

To just get it sorted you can do this: 要对其进行排序,可以执行以下操作:

sorted_stuff = sorted([(ord(x[0]), x, y) for x, y in d.items()])
final_sorted = [(y,z) for x,y,z in sorted_stuff]

The sorted_stuff will look like this: sorted_stuff将如下所示:

[(77, 'Mary XXIV', 24), (82, 'Robert III', 3)]

The final_sorted will be formatted properly: final_sorted将被正确格式化:

[('Mary XXIV', 24), ('Robert III', 3)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM