sorting with two key= arguments

落花浮王杯 提交于 2021-02-10 12:12:29

问题


I want a case-insensitive sort of a tuple of records (lists) on two fields in each record. HowTo/Sorting tells me how to do case-insensitive (key=str.lower), and it tells me how to sort on two keys (key=operator.itemgetter(0,1)). I tried the following:

parts = [
    ('A',2,''),
    ('a',1,''),
    ('b',2,''),
    ('B',1,''),
]
foo = sorted(parts, key=str.lower, key=operator.itemgetter(0,1))
print(foo)

Python does not like two key=s in the same sorted. It says: SyntaxError: keyword argument repeated, pointing to the second instance of key=.

How can I get a case-insensitive sort, and sort on multiple fields, too?


回答1:


The problem with your code is that you pass the same parameter twice. That is not possible.

They key argument of sorted expects a function. This function gets one element of the iterable and returns something that is sortable in the way you want.

Commonly, lambda functions (that means inline-functions) are used:

parts = [('A', 2, ''),
         ('a', 1, ''),
         ('b', 2, ''),
         ('B', 1, '')]
foo = sorted(parts, key=lambda s: (s[0].lower(), s[1]))
print(foo)

But you could also create a "real" function:

parts = [('A', 2, ''),
         ('a', 1, ''),
         ('b', 2, ''),
         ('B', 1, '')]

def my_sorting(element):
    return (element[0].lower(), element[1])

bar = sorted(parts, key=my_sorting)
print(bar)

Both give

[('a', 1, ''), ('A', 2, ''), ('B', 1, ''), ('b', 2, '')]

You should also know that tuples are always sorted element by element. That means, first the list is sorted by the first element of all tuples. Then, for elements which have the same sorting key for the first element, the second element is used, etc.



来源:https://stackoverflow.com/questions/36770509/sorting-with-two-key-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!