Looking for minimum, maximum and average values ​​for nested lists?

So, I have these lists:

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]

Format: [player name, first round score, second round score]

How to write code to find the maximum value, as well as the average value for the first and second points, respectively?

EDIT: I think I might have to type “name of players with the highest score” instead of “highest score”, but I don't know how to do this: \

+5
source share
3 answers

Maximum value:

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

Lowest value:

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

Average values ​​for each player:

[float(p[1] + p[2]) / 2 for p in PlayerList]

ETA: for your comment, the name of the player with the highest rating:

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

Max. and min:

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

The average is a little dirtier:

>>> [(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
source

:

(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 )

If instead you want the players with the highest and lowest final score, just replace max(a, b)and min(a, b)on a + b.

Please note that this selects one best / worst player, even if there is a tie.

Find the average values ​​of the first and second points:

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

All Articles