Luke Bray Luke Bray - 1 month ago 8
Python Question

How to count values in a list Python 3

I have code like this:

winners = [red, blue, yellow]

player_1_guesses = [red, green, orange]
player_2_guesses = [red, blue, orange]
player_3_guess = [red, green, yellow]


I'd like to count how many times each value in
winners
appears across the three
player_x_guesses
lists. So I would expect to see something like:

totals = {'red': 3, 'blue': 1, 'yellow': 1}


I'm not really sure what this kind of data analysis (?) is called or even what to google to achieve what I want.

Thanks for any help.

Answer

Try doing this:

all_guesses = player_1_guess + player_2_guess + player_3_guess
dct = {i:all_guesses.count(i) for i in winners}

output:

{'blue': 1, 'yellow': 1, 'red': 3}

Using collections:

from collections import Counter

dct = Counter(word for word in all_guesses if word in winners)
Comments