I have a list of lists that looks like this
l1 = [[1,'steve'],[4,'jane'],[3,'frank'],[2,'kim']]
and I want to order them by the first number
how would i go about this, thank you
I have a list of lists that looks like this
l1 = [[1,'steve'],[4,'jane'],[3,'frank'],[2,'kim']]
and I want to order them by the first number
how would i go about this, thank you
By default, sorted
will use the first element:
>>> l1 = [[1,'steve'],[4,'jane'],[3,'frank'],[2,'kim']]
>>> sorted(l1)
[[1, 'steve'], [2, 'kim'], [3, 'frank'], [4, 'jane']]
As noted in the comments, l1.sort()
will sort the original list in place, and is a better option if you don't need to preserve the original order.
This is the way the comparison operators work in Python:
>>> [1, 'something'] < [2, 'something']
True
Note that if the first element compares as equal, it will compare the second element, and so on:
>>> [1, 1, 1] < [1, 1, 2]
True
This means that two names with the same number would be sorted (lexicographically) by the string, not in place:
>>> sorted([[1, 'mike'], [1, 'bob']])
[[1, 'bob'], [1, 'mike']]
Python sort will compare the lists with the first element by default. If they're the same, it will continue with the second element, and so on.
so
l1.sort()
will do.
But if you really just want to sort by first value and nothing else :
sorted(l1, key=lambda id_and_name: id_and_name[0])
#=> [[1, 'steve'], [2, 'kim'], [3, 'frank'], [4, 'jane']]
l1.sort(key=lambda x: int(x[0]))
Should do the trick make sure you have the int() cast as you can run into further errors with larger numbers because the integers are lexicographically compared. i.e., '5'
will be larger than '20'
from operator import itemgetter
l1 = [[1,'steve'],[4,'jane'],[3,'frank'],[2,'kim']]
l1 = sorted(l1, key=itemgetter(0))
l1 = [[1,'steve'],[4,'jane'],[3,'frank'],[2,'kim']]
ol = sorted(l1, key=lambda key_value: key_value[0])
print (ol)
output:
[[1, 'steve'], [2, 'kim'], [3, 'frank'], [4, 'jane']]
Try the following:
l1 = [[1,'steve'],[4,'jane'],[3,'frank'],[2,'kim']]
sorted_l1 = sorted(l1, key=lambda item: item[0]) # Or simply sorted(l1)
Output:
>>> sorted_l1
[[1, 'steve'], [2, 'kim'], [3, 'frank'], [4, 'jane']]
If you want to update the same list (to be sorted), try the following:
>>> l1.sort(key=lambda item: item[0]) # Or simply l1.sort()
>>> l1
[[1, 'steve'], [2, 'kim'], [3, 'frank'], [4, 'jane']]