Sub-sorting lists in Python3
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I would like to sub-sort list_a by the 3rd column/position. list_a is already sorted by column/position 2, I just need the sub-sort on column/position 3. The result should look like whats in list_b.

list_a=[
    ['Arch', '#1 ', 11, '  3.36'], 
    ['PM', '#2 ', 10, '   2.20'], 
    ['PM', '#3 ', 10, '   2.80'], 
    ['PM', '#4 ', 10, '   2.85'], 
    ['PM', '#5', 10, '    3.00' ],
    ['PM', '#6', 10, '   3.10' ], 
    ['SD', '#7 ', 9, '   2.67' ], 
    ['I&O', '#8 ', 9, '   2.89']
] 

list_b=[
    ['Arch', '#1 ', 11, '   3.36'], 
    ['PM', '#6', 10, '      3.10' ],
    ['PM', '#5', 10, '      3.00' ],
    ['PM', '#4 ', 10, '     2.85'], 
    ['PM', '#3 ', 10, '     2.80'],
    ['PM', '#2 ', 10, '     2.20'], 
    ['PM', '#3 ', 10, '     2.80'], 
    ['I&O', '#8 ', 9, '     2.89'],
    ['SD', '#7 ', 9, '      2.67' ]
] 
Tags
python3

Crowdsource coding tasks.

1 Solution


Solution

list_a=[
['Arch', '#1 ', 11, ' 3.36'],
['PM', '#2 ', 10, ' 2.20'],
['PM', '#3 ', 10, ' 2.80'],
['PM', '#4 ', 10, ' 2.85'],
['PM', '#5', 10, ' 3.00' ],
['PM', '#6', 10, ' 3.10' ],
['SD', '#7 ', 9, ' 2.67' ],
['I&O', '#8 ', 9, ' 2.89']
]

// Ascending
list_b = sorted(list_a, key=lambda x: x[3])

// Descending
list_b = sorted(list_a, key=lambda x: x[3], reverse=True)

print(list_b)

Descending is is your list_b example.
VladimirMikulic 5 months ago
Beautiful, I knew it had to be something simple. Thanks!
broadreach 5 months ago
You're welcome. By the way, you have one extra space ( ) in #5 example entry. Each entry has 3 spaces, but this one has 4 spaces before the value (3.00). That can cause problems with sorting because of inconsistency, so keep that in mind :)
VladimirMikulic 5 months ago