0

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.

3
  • why don't you keep a single dictionary instead of separate variables for guesses? Commented Oct 3, 2016 at 14:23
  • 1
    You could use the Counter collection : docs.python.org/3/library/collections.html#collections.Counter Commented Oct 3, 2016 at 14:24
  • 1
    Are those list items supposed to be strings? If so, you need to put them in quotes. As for your actual question, I agree with jobou that you should take a look at collections.Counter Commented Oct 3, 2016 at 14:26

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, both of these will work. What is this 'topic' called so I can research it more to see how your code works?
The first one is called Dictionary Comprehension, second one's just using an existing module.
0

Not sure if I'm breaking the rules here, but my approach was to search for "python compare string arrays" and I got this: Compare string with all values in array

You have one list/array of strings that you want to compare with three other lists/arrays.

Assuming you want to know how many players guessed the correct colour and in the right position. In other words player_1_guesses = [green, red, orange] would not count as a correct guess for red because it's not in the first position, for your example.

In my head, the logic of your code would go like this (this isn't python code by the way!):

  1. get winners[0], which is 'red'
  2. check winners[0] against values in player_n_guesses[0] and record the outcome in a variable called red (e.g. if player_n_guesses[0]==winners[0]:red +=1)

  3. use nested for loops to go through everything, then make your totals list using the format method.

I expect there's a more efficient way that directly compares matrices - try searching for 'string matrix comparison python' or something like that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.