DarsAE
DarsAE

Reputation: 185

Finding 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]

The format is [Player's name, first round score, second round score]

How to write a code to find the highest value, as well as the average for first and second scores respectively?

EDIT: I think I might need to print the 'name of the players with the highest score' instead of the 'highest score' but I don't know how to do that :\

Upvotes: 5

Views: 10430

Answers (3)

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

To find the players with the highest and lowest score in any round:

(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 total scores, simply replace max(a, b) and min(a, b) with a + b.

Note that this picks a single best/worst player, even if there's a tie.

To find averages of the first and second scores:

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

Upvotes: 1

David Robinson
David Robinson

Reputation: 78600

Highest value:

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

Lowest value:

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

Averages for each player::

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

ETA: Per your comment, the name of the player with the highest score:

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

Upvotes: 9

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29727

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]

Average is a bit 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)]

Upvotes: 1

Related Questions