查找嵌套列表的最小值、最大值和平均值?

5

我有这些列表:

Player1 = ["Ryan", 24, 19]
Player2 = ["Jamie", 22, 24]
Player3 = ["Alicia", 17, 15]
Player4 = ["Dominique", 13, 11]
Player5 = ["Michael", 18, 23]

PlayerList = [Player1, Player2, Player3, Player4, Player5]

格式为[选手姓名、第一轮得分、第二轮得分]

如何编写代码查找第一轮和第二轮的最高分以及平均分?

编辑:我认为我可能需要打印出'得分最高的选手的姓名'而不是'最高分数',但我不知道怎么做:\


4
只是说,现在或许是写一个“玩家”类的时候了。 - Rik Poggi
如果有并列的最高分,该怎么办呢? - fraxel
1
...或者至少一个元组,从概念上讲比列表更合适。 - tokland
3个回答

9

最高值:

max(max(p[1:]) for p in PlayerList)

最低值:

min(min(p[1:]) for p in PlayerList)

每个球员的平均数据:
[float(p[1] + p[2]) / 2 for p in PlayerList]

预计时间:根据您的评论,得分最高的玩家名称:

max(PlayerList, key=lambda p: max(p[1:]))[0]

你可以直接调用 max(max(p[1:]) for p in PlayerList) - kennytm
真的,作为一个生成器,它会更快(略微)。 - David Robinson
@KennyTM 有没有办法我可以同时打印出得分最高的玩家名字呢? - DarsAE

1

最大值和最小值:

>>> max(PlayerList, key=lambda p: max(p[1:]))
['Ryan', 24, 19]
>>> min(PlayerList, key=lambda p: min(p[1:]))
['Dominique', 13, 11]

平均值有点儿复杂:

>>> [(p[0], sum(p[1:]) / 2.) for p in PlayerList]
[('Ryan', 21.5), ('Jamie', 23.0), ('Alicia', 16.0), ('Dominique', 12.0), ('Michael', 20.5)]

1

查找任何一轮中得分最高和最低的玩家:

(max_score, max_player) = max( (max(a, b), player) for (player, a, b) in players )
(min_score, min_player) = min( (min(a, b), player) for (player, a, b) in players )

如果你想要最高和最低总分的选手,只需将max(a, b)min(a, b)替换为a + b

请注意,这会选择单个最佳/最差的选手,即使存在平局。

要找到第一和第二得分的平均值:

avg_round1 = float(sum( a for (_, a, _) in players )) / len(players)
avg_round2 = float(sum( b for (_, _, b) in players )) / len(players)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接