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 :\
Python doesn't have a built-in function to calculate an average of a list, but you can use the sum() and len() functions to calculate an average of a list.
To find the shape (or dimensions) of a nested list or tuple in Python, iterate over each element in the list or tuple and identify its length with the built-in len() function.
Method #1: Using max() + min() + “+” operator The maximum and minimum values can be determined by the conventional max and min function of python and the extension of one to two lists can be dealt using the “+” operator.
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]
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)]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With