-1

I would like to sort a list of tuples, and get the 3 tuples with the biggest values. The tuples are made like this : ('String', int)

Sample I/O:

Input:

wins_list = [("jim", 11), ("pam", 9), ("dwight", 12), ("oscar", 2), ("micheal", 17), ("angela", 3), ("kevin", 1)]

Expected Output:

["micheal", "dwight", "jim"]

Input:

wins_list = [("jim", 1), ("pam", 4), ("jan", 10), ("creed", 7), ("micheal", 5), ("meredith", 2), ("phyllis", 28)]

Expected Output:

["phyllis", "jan", "creed"]
Malo
  • 1,233
  • 1
  • 8
  • 25
  • Possible duplicate of https://stackoverflow.com/questions/13145368/find-the-maximum-value-in-a-list-of-tuples-in-python – FastDeveloper Nov 22 '20 at 13:38
  • Does this answer your question? [Finding max value in the second column of a nested list?](https://stackoverflow.com/questions/4800419/finding-max-value-in-the-second-column-of-a-nested-list) – vvvvv Nov 22 '20 at 13:40

2 Answers2

0

A one liner from the doc example : https://docs.python.org/fr/3/howto/sorting.html

[t[0] for t in sorted(wins_list, key=lambda winner: winner[1], reverse=True)[0:3]]
Malo
  • 1,233
  • 1
  • 8
  • 25
0
def pick_winners(lst):
    lst = sorted(lst, key=lambda x: x[1], reverse=True)
    return [x[0] for x in lst[:3]]

A more verbose solution.

JLeno46
  • 1,186
  • 2
  • 14
  • 29
  • Hi JLeno46.First, I am really thabkful for your answer. I am very new in these codding and pyhton thing and I tried to get appropriate output for first input in my example but I couldn't do that. I wrote your answer like: – Serhat Hakan Can Akdaş Nov 22 '20 at 14:15
  • def pick_winners(lst): lst = sorted(lst, key=lambda x: x[1], reverse=True) return [x[0] for x in lst[:3]] pick_winners(input()) and give input as wins_list = [("jim", 11), ("pam", 9), ("dwight", 12), ("oscar", 2), ("micheal", 17), ("angela", 3), ("kevin", 1)] but I couldn't solve that. What should I do,thanks for your asnwer and time mate. – Serhat Hakan Can Akdaş Nov 22 '20 at 14:18
  • @Serhat Hakan Can Akdaş If you already stored your list in the variable wins_list there's no need to use an input, just call pick_winners(wins_list). You can print the results with print(pick_winners(wins_list)) – JLeno46 Nov 22 '20 at 14:42
  • But In this question it is said that give an input like wins_list=[blabla...].Then how can I write the variable part of my input in parentheses of pick_winners – Serhat Hakan Can Akdaş Nov 22 '20 at 15:02
  • You have to copy/paste your list in your console (or write it), also give a prompt to your input like this: pick_winners(input('insert list here: ')) – JLeno46 Nov 22 '20 at 15:16