-2

I have a list as follows:

original_list = [u'0.1.876',u'0.1.1102']

I need to sort this in reverse order, so I did the following:

sorted_list = sorted(original_list, reverse=True)

The output is [u'0.1.876',u'0.1.1102'], but i need the sorting to consider the last column of digits. So expected output is [u'0.1.1102',u'0.1.876']. Any suggestions on how i could get this done ?

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
user3228188
  • 1,641
  • 3
  • 14
  • 19

3 Answers3

2

You can use rfind to index of the last ., cast to int:

original_list = [u'0.1.876',u'0.1.1102']

srt = sorted(original_list,key=lambda x: int(x[x.rfind(".")+1:]),reverse=True))
Mazdak
  • 105,000
  • 18
  • 159
  • 188
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1
In [50]: original_list = [u'0.1.876',u'0.1.1102']

In [51]: sorted(original_list, reverse=True, key=lambda s: int(s.rsplit('.',1)[1]))
Out[51]: ['0.1.1102', '0.1.876']
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
0

Assuming by last column you mean the substring followed by the last dot, and that you are interested in numerical comparison, you can use the key parameter of sorted as follows:

original_list = [u'0.1.876',u'0.1.1102']
sorted(original_list, key=lambda x: int(x.split('.')[-1]), reverse=True)

Output:

[u'0.1.1102', u'0.1.876']
YS-L
  • 14,358
  • 3
  • 47
  • 58
  • `sorted(original_list, key=lambda x: int(x.split('.')[-1]))` in case of values 00001 etc – user3636636 Jul 16 '15 at 09:52
  • 1
    This has all the hallmarks of answering *exactly what was asked* without actually answering what is probably intended. If I were to guess, the questioner also wants `1.0.1` and `0.2.1` to be sorted ahead of `0.1.1102`. – Phylogenesis Jul 16 '15 at 09:55
  • Funny - I've seen answers get voted down for doing exactly what you are suggesting - guessing at the intent, rather than actually answering the question *as asked*. – SiHa Jul 16 '15 at 10:02
  • Possibly, but I didn't downvote the answer, I just added some critique. – Phylogenesis Jul 16 '15 at 10:03