1

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.4881723880136537],
['39.9767607107', '-75.1328155113', 'Asphalt', '20', 1.5123970222417986],
['40.089750884', '-74.9852538861', 'Paved', ' ', 4.296923142303416]]

Where the indices are latitude, longitude, type of pavement, no. of empty spots, and location in KM from my current location

I want to sort this unsorted list from the greatest to lowest by my 4-th index, which is the location in KM from my current location. You can assume that the list-within-list will will contains the same total number of data points of five.

I know to use sort() for single-dimensional lists, but I am not quite sure how to sort lists within lists.

Any assistance is appreciated.

1

3 Answers 3

3

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])
Sign up to request clarification or add additional context in comments.

Comments

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]]

Comments

1

There is a key argument in sort:

from operator import itemgetter
data.sort(key=itemgetter(4))

1 Comment

And operator.itemgetter() is also documented here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.