Sort a list by multiple attributes?

前端 未结 6 2089
后悔当初
后悔当初 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:13

    I'm not sure if this is the most pythonic method ... I had a list of tuples that needed sorting 1st by descending integer values and 2nd alphabetically. This required reversing the integer sort but not the alphabetical sort. Here was my solution: (on the fly in an exam btw, I was not even aware you could 'nest' sorted functions)

    a = [('Al', 2),('Bill', 1),('Carol', 2), ('Abel', 3), ('Zeke', 2), ('Chris', 1)]  
    b = sorted(sorted(a, key = lambda x : x[0]), key = lambda x : x[1], reverse = True)  
    print(b)  
    [('Abel', 3), ('Al', 2), ('Carol', 2), ('Zeke', 2), ('Bill', 1), ('Chris', 1)]
    

提交回复
热议问题