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

时间:2012-03-25 08:12:22

标签: python list

所以我有这些清单:

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]

格式为[玩家姓名,第一轮评分,第二轮评分]

如何编写代码以找到最高值,以及分别获得第一和第二分数的平均值?

编辑:我想我可能需要打印'得分最高的球员的名字'而不是'最高​​得分',但我不知道该怎么做:\

3 个答案:

答案 0 :(得分: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]

ETA:根据您的评论,得分最高的玩家名称:

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

答案 1 :(得分: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)]

答案 2 :(得分: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)