1

I want to show the list from the large age to the small age.   Here is my list:  

player = [("Dmitry", 15), ("Dima", 11), ("Sergey", 14), ("Andrey", 12), ("Nikita", 13)]

  I can sort list using name element by player.sort and get this list:  

[('Andrey',12),('Dima',11),('Dmitry',15),('Nikita',13),('Sergey',14)]

  But I want this list, where ages are large age to small age:  

[('Dmitry',15),('Sergey',14),('Nikita',13),('Andrey',12),('Dima',11)]

  How I can do this?

Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
Ramzes666
  • 21
  • 2

4 Answers4

1

Use sorted with key and reverse

Ex:

player = [("Dmitry", 15), ("Dima", 11), ("Sergey", 14), ("Andrey", 12), ("Nikita", 13)]
print( sorted(player, key=lambda x: x[1], reverse=True) )

Output:

[('Dmitry', 15), ('Sergey', 14), ('Nikita', 13), ('Andrey', 12), ('Dima', 11)]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

You can achieve your desired sort by using the itemgetter() function as the key parameter and also setting reversed to true so the list is in decending order:

>>> from operator import itemgetter
>>> players = [("Dmitry", 15), ("Dima", 11), ("Sergey", 14), ("Andrey", 12), ("Nikita", 13)]
>>> players.sort(key=itemgetter(1), reverse=True)
>>> print(players)
[('Dmitry', 15), ('Sergey', 14), ('Nikita', 13), ('Andrey', 12), ('Dima', 11)]
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
1

You need to pass a lambda expression as argument for sorted method.

sorted_list = sorted(player, key=lambda tup: tup[1], reverse=True)

Output

[('Dmitry', 15), ('Sergey', 14), ('Nikita', 13), ('Andrey', 12), ('Dima', 11)]
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
1

Another way using lambda but without reverse=True:

player = [("Dmitry", 15), ("Dima", 11), ("Sergey", 14), ("Andrey", 12), ("Nikita", 13)]
player.sort(key=lambda x: -x[1])

# [('Dmitry', 15), ('Sergey', 14), ('Nikita', 13), ('Andrey', 12), ('Dima', 11)]
Austin
  • 25,759
  • 4
  • 25
  • 48