Skip to content Skip to sidebar Skip to footer

Sorting List-within-list In Python

I have a list within a list that is in this format: [['39.9845450804', '-75.2089337931', 'Paved', ' ', 5.974380011873201], ['39.977111208', '-75.1326105278', 'Asphalt', '8', 3.4881

Solution 1:

If my_data is your list then to sort by the 5th element in my_data you do:

sorted(my_data, key=lambda data: data[4])

Solution 2:

Use the key parameter:

a = [['39.9845450804', '-75.2089337931', 'Paved', ' ', 5.974380011873201],
['39.977111208', '-75.1326105278', 'Asphalt', '8', 3.4881723880136537],
['39.9767607107', '-75.1328155113', 'Asphalt', '20', 1.5123970222417986],
['40.089750884', '-74.9852538861', 'Paved', ' ', 4.296923142303416]]

sorted(a, key=lambda entry: entry[4])

Gives:

[['39.9767607107', '-75.1328155113', 'Asphalt', '20', 1.5123970222417986], ['39.977111208', '-75.1326105278', 'Asphalt', '8', 3.4881723880136537], ['40.089750884', '-74.9852538861', 'Paved', ' ', 4.296923142303416], ['39.9845450804', '-75.2089337931', 'Paved', ' ', 5.974380011873201]]

Solution 3:

There is a key argument in sort:

from operatorimport itemgetter
data.sort(key=itemgetter(4))

Post a Comment for "Sorting List-within-list In Python"