mrpbennett
mrpbennett

Reputation: 1956

comparing two lists but then saying how many times an item in a list matched

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

Upvotes: 1

Views: 124

Answers (3)

Endyd
Endyd

Reputation: 1279

You can iterate through each list of previous_winners and call the intersection of sets, then go through each intersection of compare and count up each time a match was found into a dict.

matches = {}
for prev in previous_winners:
    compare = set(winning_numbers) & set(prev)
    for match in compare:
        matches[match] = matches.get(match, 0) + 1

for k, v in matches.items():
    print(k, 'occurred', v, 'times')

Output:

4 occurred 3 times
2 occurred 2 times

Upvotes: 0

blhsing
blhsing

Reputation: 106568

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})

Upvotes: 2

yatu
yatu

Reputation: 88236

You can use chain.from_iterable to flatten previous_winners and create a dictionary with a list comprehension and using .count to count each occurrence in previous_winners:

l = list(chain.from_iterable(previous_winners))
{i:l.count(i) for i in winning_numbers}
{20: 0, 49: 0, 47: 0, 40: 0, 36: 0, 4: 3, 2: 2}

Upvotes: 1

Related Questions