I’ve got three tuples in a list, if I’m correct, and I’m trying to return the ranking of the three best player of a given game. Considering the following:
players_score = [ ('Joe', 100, 34, 38, 90, 67, 3, 10),
('Bob', 90, 38, 4, 100, 60, 4, 11),
('May', 80, 36, 40, 91, 70, 2, 12),
('Anna', 95, 32, 36, 92, 68, 8, 13) ]
Printing the results of game one returns the following score:
[('Joe', 100), ('Bob', 90), ('May', 80), ('Anna', 95)]
But instead, I would like to have the program print this:
[ ('Joe', 1), ('Anna', 2), ('Bob', 3) ]
Since Joe has 100 points, Anna has 95 and Bob has 90.
I'm thinking about using enumerate()
, but I figured I may be better of by first converting the tuples to a dictionary, which I tried in the last part of my code, but without much luck.
I started trying the following:
#prints the corresponding score with the player.
game = int(input("Please enter the number of a game: "))
game_score = [ (p[0], p[game]) for p in players_score]
print(game_score)
#prints a list of results ordered from high to low.
score_list = []
for p in players_score:
score_list.append(p[game])
score_list.sort(reverse=True)
print(score_list)
#prints only the name and the result of the first game
list = [ (name, first) for name, first, second, third, fourth, sixth, seventh, eighth in players_score ]
print(list)
#trying to get a convert from a tuple to a dict.
for name, first, second, third, forth, sixth, seventh, eighth in players_score:
dict(name, first)
print(dict)
You have this:
a = [('Joe', 100), ('Bob', 90), ('May', 80), ('Anna', 95)]
Try to sort this with the second parameter of each tuple:
a = sorted(a, key=lambda x:x[1], reverse=True)
then:
result = [(v[0], i+1) for i,v in enumerate(a)][0:3]
the output will be:
[('Joe', 1), ('Anna', 2), ('Bob', 3)]