0

I have been struggling to sort or rearrange the lists. I would want to sort the lists in descending order based on the numbers(last element within the list).
So, ideally, the list with (297539) will be on top; while the list with (234933) will be at bottom:

[...., '297539']
[..]
[..]
[...., '234933']

Can someone help me with this? Thanks alot. This is what I have done so faroutput

yatu
  • 86,083
  • 12
  • 84
  • 139
Joker
  • 29
  • 4

2 Answers2

3

Use sorted with a custom key function:

# example list
l = [['a', '297539'],['sas', '257539'],['absdas', '287539'],['xasd', '234933']]
sorted(l, key=lambda x: int(x[-1]), reverse=True)
# [['a', '297539'], ['absdas', '287539'], ['sas', '257539'], ['xasd', '234933']]
yatu
  • 86,083
  • 12
  • 84
  • 139
  • How is `int` redundant @Nihal? strings are sorted lexicographically, i.e.`'9' > '12'`, so the numbers must be turned to ints, otherwise only the first digit is considered – yatu Apr 30 '19 at 07:41
  • you are right, sry my mistake – Nihal Apr 30 '19 at 07:42
  • you can also use `sorted(a,key =lambda x:int(itemgetter(1)(x)))` – sahasrara62 Apr 30 '19 at 08:14
  • `itemgetter` is interesting when it can be used to avoid a `lambda` function, as operations are kept on the `C` side, which is not this case @prashantrana – yatu Apr 30 '19 at 12:04
1

using itemgetter you can handle loop

from operator import itemgetter
a = [['a', '297539'],['sas', '257539'],['absdas', '287539'],['xasd', '234933']]
a = sorted(a, key=itemgetter(1),reverse=True)
print(a)
Zaynul Abadin Tuhin
  • 31,407
  • 5
  • 33
  • 63
  • 1
    itemgetter is better than using a lambda function , good solution, no idea why you recive a negative upvote – sahasrara62 Apr 30 '19 at 07:47
  • 2
    Not me @prashantrana, but the problem I see here is that, as mentioned as a comment this is sorting lexicographically (as the numbers are strings), meaning that when sorting numbers `'9' > '12'`, which presumably is not what OP wants? – yatu Apr 30 '19 at 07:50
  • @yatu, i didn't try that out. you are right this method failed in that case. `sorted(a,key =lambda x:int(itemgetter(1)(x)))` improvement to existing solution. using lambda i guess your answer is much better . – sahasrara62 Apr 30 '19 at 08:14