我正在尝试将winning_numbers
与较大的previous_winners
列表进行比较,然后得出某个数字出现多少次的计数。
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]
]
我一直在尝试以下
compare = set(winning_numbers) & set(previous_winners)
print(compare)
但是它会产生错误TypeError: unhashable type: 'list'
,除非我在previous_winners
上使用单个列表,例如给出{4, 2}
但...如何计数这些数字的次数出现在previous_winners
列表中?
我想最终打印出类似“我们匹配4个,它被匹配8次”之类的内容
答案 0 :(得分:2)
您可以展平previous_winners
列表,并使用collections.Counter
来计算每个数字的出现次数,以便您可以迭代winning_numbers
来生成中奖号码与其号码的对应关系在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})
这将输出:
{20: 0, 49: 0, 47: 0, 40: 0, 36: 0, 4: 3, 2: 2}
或者,如果您只希望以前出现的数字,则将winning_numbers
首先设为集合,并仅对集合中的那些数字从previous_winners
中产生计数会稍微有效率:< / p>
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))
这将输出:
Counter({4: 3, 2: 2})
答案 1 :(得分:1)
您可以使用chain.from_iterable
展平previous_winners
并使用list comprehension
创建字典,并使用.count
来计数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}
答案 2 :(得分:0)
您可以遍历previous_winners
的每个列表并调用集合的交集,然后遍历compare
的每个交集并在每次发现匹配项时计数。
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')
输出:
4 occurred 3 times
2 occurred 2 times