知道几个项目的顺序自定义排序列表

时间:2017-05-18 11:14:08

标签: python list sorting

我想使用自定义订单对列表进行排序,只知道几个项目的顺序。在订单无关紧要的情况下,其余项目应被视为“其他”。

例如,我有以下列表,我尝试对几个项目进行排序。以下代码将因KeyError而失败,因为它无法找到Badminton或Cricket。

myList = ['Football', 'Baseball', 'Basketball', 'Badminton', 'Cricket']

myOrder = {"Baseball" : 1, "Basketball" : 2, "Football" : 3}

myList.sort(key=lambda val: myOrder[val])

如何在不关心订单的情况下考虑列表中的其他项目?

1 个答案:

答案 0 :(得分:3)

在Python 2中,您可以使用myOrder.get作为排序键,因为None(默认值get返回)总是小于任何整数:

>>> myList = ['Football', 'Baseball', 'Basketball', 'Badminton', 'Cricket']
>>> myOrder = {"Baseball" : 1, "Basketball" : 2, "Football" : 3}
>>> myList.sort(key=myOrder.get)
>>> myList
['Badminton', 'Cricket', 'Baseball', 'Basketball', 'Football']

在Python 3中,您无法订购NoneTypeint,因此您必须将评论中的get包含在另一个函数中,例如user234461的解决方案:

myList.sort(key=lambda val: myOrder.get(val, 0))
  

谢谢!是否可以将它们放在新排序列表的末尾?

当然,您可以使用float('inf')作为get调用的默认值:

>>> myList = ['Football', 'Baseball', 'Basketball', 'Badminton', 'Cricket']
>>> myList.sort(key=lambda x: myOrder.get(x, float('inf')))
>>> myList
['Baseball', 'Basketball', 'Football', 'Badminton', 'Cricket']

编辑2:或者您可以使用myOrder将默认排序烘焙到defaultdict词典中。我喜欢那样。

>>> from collections import defaultdict
>>> myList = ['Football', 'Baseball', 'Basketball', 'Badminton', 'Cricket']
>>> myOrder = defaultdict(lambda: float('inf'))
>>> myOrder.update({"Baseball" : 1, "Basketball" : 2, "Football" : 3})
>>> myList.sort(key=myOrder.__getitem__)
>>> myList
['Baseball', 'Basketball', 'Football', 'Badminton', 'Cricket']