Sort a list by multiple attributes?

前端 未结 6 2054
后悔当初
后悔当初 2020-11-22 02:48

I have a list of lists:

[[12, \'tall\', \'blue\', 1],
[2, \'short\', \'red\', 9],
[4, \'tall\', \'blue\', 13]]

If I wanted to sort by one e

6条回答
  •  故里飘歌
    2020-11-22 03:14

    A key can be a function that returns a tuple:

    s = sorted(s, key = lambda x: (x[1], x[2]))
    

    Or you can achieve the same using itemgetter (which is faster and avoids a Python function call):

    import operator
    s = sorted(s, key = operator.itemgetter(1, 2))
    

    And notice that here you can use sort instead of using sorted and then reassigning:

    s.sort(key = operator.itemgetter(1, 2))
    

提交回复
热议问题