Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding minimum, maximum and average values for nested lists?

Tags:

python

list

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 :\

like image 307
DarsAE Avatar asked Mar 25 '12 08:03

DarsAE


People also ask

How do you find the average of a nested list in Python?

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.

How do I find the size of a nested 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.

How do you find the max of two lists in Python?

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.


3 Answers

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]
like image 126
David Robinson Avatar answered Oct 18 '22 01:10

David Robinson


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)]
like image 43
Roman Bodnarchuk Avatar answered Oct 18 '22 02:10

Roman Bodnarchuk


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)
like image 1
Marcelo Cantos Avatar answered Oct 18 '22 01:10

Marcelo Cantos