Zoro99
Zoro99

Reputation: 185

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,'], ['my', 'choice', '20,']]

because of this I am unable to sort the list of list based on these integer values.

Is there a way I can convert all these list[2] values into integer and sort the outer list based on that? Or any other way via which I can sort this list using integers in above list.

Intended result is, output of sorted list should show as:

[['my', 'choice', '20,'], ['test', 'hello', '60,'], ['why', 'to', '500,']]

Upvotes: 1

Views: 580

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121594

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

Upvotes: 2

Related Questions