Reputation: 185
I am doing some operations on file and converting its lines to a list
l1 = [
['john', 'age', '23', 'has', 'scored', '90,'],
['sam', 'scored', '70,', 'and', 'age', 'is', '19,'],
['rick', 'failed', 'as' ,'he', 'scored', '20,'],
]
As we see not all lists/lines are similar, but one thing will be common that is integer followed by word 'scored'
.
Is there a way I can sort on the basis of integer which follows keyword 'scored'
?
Earlier I had tried with similar lists with following and it had worked but that wont help on above list
sorted(l1, key=lambda l: int(l[4].rstrip(',')),reverse=True)
Upvotes: 0
Views: 25
Reputation: 11635
Here's one way:
>>> a_list = [['john', 'age', '23', 'has', 'scored', '90,'],
['sam', 'scored', '70,', 'and', 'age', 'is', '19,'],
['rick', 'failed', 'as', 'he', 'scored', '20,']]
>>> sorted(a_list, key = lambda l: int(l[l.index('scored') + 1].strip(",")), reverse=True)
[['john', 'age', '23', 'has', 'scored', '90,'],
['sam', 'scored', '70,', 'and', 'age', 'is', '19,'],
['rick', 'failed', 'as', 'he', 'scored', '20,']]
Upvotes: 2