Sort List Of Lists By Specific Index Of Inner List
I am trying perform some operation on a file and convert its lines to list. However the integer values are also taken as string l1 = [['test', 'hello', '60,'], ['why', 'to', '500,'
Solution 1:
Use a custom sort key, to convert the last element to an integer just when sorting:
sorted(l1, key=lambda l: int(l[2].rstrip(',')))
The key
is used to produce the value on which to sort, for each element in the list. So the lambda
function is called for each element, and the above code extracts the l[2]
value, converting it to an integer. The str.rstrip()
call removes the trailing comma first.
Demo:
>>> l1 = [['test', 'hello', '60,'], ['why', 'to', '500,'], ['my', 'choice', '20,']]
>>> sorted(l1, key=lambda l: int(l[2].rstrip(',')))
[['my', 'choice', '20,'], ['test', 'hello', '60,'], ['why', 'to', '500,']]
Post a Comment for "Sort List Of Lists By Specific Index Of Inner List"