user1903357
user1903357

Reputation: 5

Converting strings to integers then ordering them in an list with strings

I have the following list and I need to order them from biggest to smallest names and numbers.

['joe:  5', 'ed:  9', 'joe:  7', 'ed:  8']

I'm having the following problems:

  1. Converting the numbers from strings to integers to order it.
  2. Ordering them with the correct string.

So my end result should be this:

['ed:  9', 'ed:  8', 'joe:  7', 'joe:  5']

Upvotes: 0

Views: 67

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251106

>>> lis=['joe:  5', 'ed:  9', 'joe:  7', 'ed:  8']

>>> sorted(lis,key=lambda x:int(x.split()[-1]),reverse=True)
>>> ['ed:  9', 'ed:  8', 'joe:  7', 'joe:  5']

you can fetch the integers in each list item using str.split(as shown below), and that integer is then used to sort the list:

>>> int(lis[0].split(":")[1])
>>> 5

#or  

>>> int(lis[0].split()[1]) 
>>> 5

Upvotes: 5

Related Questions