16

I am trying to write a program that orders a list of strings based on the last character in the item.

["Tiger 6", "Shark 4", "Cyborg 8"] are how my list is imported, but I need to put them in numerical order based on the numbers at the end.

Georgy
  • 12,464
  • 7
  • 65
  • 73
Chris Hodges
  • 161
  • 1
  • 1
  • 3

4 Answers4

21

I am trying to write a program that orders a list of strings based on the last character in the item.

>>> s = ["Tiger 6", "Shark 4", "Cyborg 8"]
>>> sorted(s, key=lambda x: int(x[-1]))
['Shark 4', 'Tiger 6', 'Cyborg 8']

Try this if there are more num of digits at the last.

>>> import re
>>> sorted(s, key=lambda x: int(re.search(r'\d+$',x).group()))
['Shark 4', 'Tiger 6', 'Cyborg 8']

re.search(r'\d+$',x).group() helps to fetch the number present at the last irrespective of preceding space.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
5
def last_letter(word):
    return word[::-1]

mylst = ["Tiger 6", "Shark 4", "Cyborg 8"]
sorted(mylst, key=last_letter)
ronith raj
  • 51
  • 1
  • 3
2
nums = ["Tiger 6", "Shark 4", "Cyborg 8"]
slist=sorted(nums,key = lambda x:x[-1])
  1. here nums is an list
  2. in slist it takes list of arguments from the list nums
  3. here lambda function takes argument from list and return it's last value(e.g. if it a first argument from nums (i.e.''Tiger 6'') and it returns 6.
  4. sorted function return a list based on lambda function.
  • When possible, please make an effort to provide additional explanation instead of just code. Such answers tend to be more useful as they help members of the community and especially new developers better understand the reasoning of the solution, and can help prevent the need to address follow-up questions. – Rajan Jun 12 '20 at 12:14
1

If the numbers are not single digits, you can try -

>>> l = ["Tiger 6", "Shark 4", "Cyborg 8", "Temporary 12"]
>>> l.sort(key = lambda x: int(x.rsplit(' ',1)[1]))
>>> l
['Shark 4', 'Tiger 6', 'Cyborg 8', 'Temporary 12']

str.rsplit(s, n) function starts splitting the string at the end towards start of the string and stops after n splits. In the above case, it only splits the string once, at a space.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176