Luke Bray Luke Bray - 2 years ago 136
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
appears across the three
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 Source

Try doing this:

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


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

Using collections:

from collections import Counter

dct = Counter(word for word in all_guesses if word in winners)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download