0

I have been trying to sort an array that looks like this:

sav = [['Name: ', 'Alex', 'Score: ', '2'], ['Name: ', 'Josh, 'Score: ', '3'], ['Name: ', 'James', 'Score: ', '1']]  

so that it appears as:

sav = [['Name: ', 'James', 'Score: ', '1'], ['Name: ', 'Alex, 'Score: ', '2'], ['Name: ', 'Josh', 'Score: ', '3']]

This would be sorting by the [3] index but as the number is a string I am not sure how to do this. (This may look like a duplicate question but I have looked around and not been able to find an answer.)

1 Answer 1

3

You could use the following lambda as the sort key:

>>> sorted(sav, key=lambda x: int(x[3]))
[['Name: ', 'James', 'Score: ', '1'],
 ['Name: ', 'Alex', 'Score: ', '2'],
 ['Name: ', 'Josh', 'Score: ', '3']]

The lambda function here picks out the element at index 3 from each list and treats it as integer (using int). The list is sorted by these integers.

If left as strings, you'd get odd results when sorting since strings are sorted in lexicographical order. For example, '12' < '8'.

This returns a sorted copy of the list sav - you can rebind the name to the sorted list:

sav = sorted(sav, key=lambda x: int(x[3]))
Sign up to request clarification or add additional context in comments.

3 Comments

When I try this the output is exactly the same (even though I looked at your code and it looked like it would work)
@zeldor You need to say sav = sorted(... so you assign the sorted list back to your variable. Or use sort(sav, key=...) to sort in place.
Thanks both of you, that worked. Turns out all of the solutions I had previously tried just needed 'sav =' !!

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.