sorted
,list.sort
接受可選key
參數。通過一個關鍵功能。該函數的返回值被用於比較,而不是原始值:
>>> from collections import namedtuple
>>> hero = namedtuple('hero', ['name', 'classes', 'level'])
>>>
>>> mainList = [
... hero(name='SirGoose', classes='Fighter', level=150),
... hero(name='Conan', classes='Barbarian', level=160),
... hero(name='KingArthur', classes='Knight', level=170)
... ]
>>> sorted(mainList, key=lambda h: (h.name, h.level))
[hero(name='Conan', classes='Barbarian', level=160),
hero(name='KingArthur', classes='Knight', level=170),
hero(name='SirGoose', classes='Fighter', level=150)]
注:這裏使用的鍵功能(lambda
)返回一個元組。元組逐個比較。如果第一項是相同的,在未來加以比較,...用operator.attrgetter
>>> ('SirGoose', 12) < ('Barbarian', 160)
False
>>> ('SirGoose', 12) < ('SirGoose', 160)
True
備選:
>>> import operator
>>> sorted(mainList, key=operator.attrgetter('name', 'level'))
[hero(name='Conan', classes='Barbarian', level=160),
hero(name='KingArthur', classes='Knight', level=170),
hero(name='SirGoose', classes='Fighter', level=150)]