0

Here is my list of tuples

[('Raven', '18'), ('Lion', '6'), ('Unassigned', '0'), ('Cobra', '6')]

I want to sort them by the value of the number in the tuple, to achieve this order.

[('Raven', '18'), ('Lion', '6'), ('Cobra', '6'), ('Unassigned', '0')]

How best is it to go about this, should I use sorted()?

finefoot
  • 9,914
  • 7
  • 59
  • 102
Lyra Orwell
  • 1,048
  • 4
  • 17
  • 46

2 Answers2

3

sorted takes a key parameter where you can specify on what basis you need the sort to happen:

lst = [('Raven', '18'), ('Lion', '6'), ('Unassigned', '0'), ('Cobra', '6')]

print(sorted(lst, key=lambda x: -int(x[1])))
# or print(sorted(lst, key=lambda x: int(x[1]), reverse=True))

# Outputs: [('Raven', '18'), ('Lion', '6'), ('Cobra', '6'), ('Unassigned', '0')]
Austin
  • 25,759
  • 4
  • 25
  • 48
2

You can use sorted, with the following key:

sorted(t, key = lambda x: int(x[1]), reverse=True)
[('Raven', '18'), ('Lion', '6'), ('Cobra', '6'), ('Unassigned', '0')]

What key is doing here is to apply the defined lambda function to each element in the list prior to sorting. Consider the following equivalent using a list comprehension:

t = [int(x[1]) for x in t] 
# [18, 6, 0, 6]

And then it sorts the list of tuples using this key:

sorted(t, reverse=True)
[18, 6, 6, 0]
yatu
  • 86,083
  • 12
  • 84
  • 139