I am trying to compare winning_numbers
against the larger list of previous_winners
then get the count of how many times a certain number turned up.
winning_numbers = [20, 49, 47, 40, 36, 4, 2]
previous_winners = [
[1, 8, 11, 25, 28, 4, 6],
[13, 16, 34, 35, 45, 10, 12],
[4, 5, 8, 31, 43, 2, 9],
[2, 12, 15, 34, 50, 3, 4]
]
I have been trying the following
compare = set(winning_numbers) & set(previous_winners)
print(compare)
But it gives the ERROR TypeError: unhashable type: 'list'
unless I use a single list on previous_winners
which gives for example {4, 2}
BUT...how can I give the count of how many times those numbers showed up in the previous_winners
list?
I would like to end up printing out something like 'we match 4 and it was matched 8 times' etc
You can flatten the previous_winners
list and use collections.Counter
to count the number of occurrences of each number, so that you can iterate through winning_numbers
to produce a mapping of winning numbers to their counts in previous_winner
:
from collections import Counter
counts = Counter(n for l in previous_winners for n in l)
print({n: counts.get(n, 0) for n in winning_numbers})
This outputs:
{20: 0, 49: 0, 47: 0, 40: 0, 36: 0, 4: 3, 2: 2}
Or if you only want numbers that did appear previously, it would be slightly more efficient to make winning_numbers
a set first and produce counts from previous_winners
only for those numbers that are in the set:
from collections import Counter
winning_set = set(winning_numbers)
print(Counter(n for l in previous_winners for n in l if n in winning_set))
This outputs:
Counter({4: 3, 2: 2})