如果我是正确的话,我在列表中有3个元组,并且我试图返回给定游戏中3个最佳玩家的排名。考虑以下内容:
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) ]
打印游戏一的结果将返回以下分数:
[('Joe', 100), ('Bob', 90), ('May', 80), ('Anna', 95)]
但是,我想让程序打印以下内容:
[ ('Joe', 1), ('Anna', 2), ('Bob', 3) ]
由于乔获得100分,安娜获得95分,鲍勃获得90分。
我正在考虑使用enumerate()
,但是我认为将元组转换为字典是更好的选择,我在代码的最后部分尝试了该字典,但是运气不佳。我开始尝试以下方法:
#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)
你有这个:
a = [('Joe', 100), ('Bob', 90), ('May', 80), ('Anna', 95)]
尝试使用每个元组的第二个参数对它进行排序:
a = sorted(a, key=lambda x:x[1], reverse=True)
然后:
result = [(v[0], i+1) for i,v in enumerate(a)][0:3]
输出将是:
[('Joe', 1), ('Anna', 2), ('Bob', 3)]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句