python - 比较两个列表,然后说出列表中某个项目匹配的次数

标签 python list numbers comparison

我正在尝试将 获胜数字 与更大的 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 次”等内容

最佳答案

您可以展平 previous_winners 列表,并使用 collections.Counter 来计算每个数字出现的次数,以便您可以迭代 winning_numbers code> 生成中奖号码到 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}

或者,如果您只需要之前出现过的号码,那么首先将 looking_numbers 设为一组,然后仅针对那些出现过的号码从 previous_winners 中生成计数会稍微更有效在集合中:

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

关于python - 比较两个列表,然后说出列表中某个项目匹配的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54028899/

相关文章:

objective-c - 在 Objective-C 中处理整数

Oracle:to_char(number) 的模式以添加额外的 ascii 字符?

javascript - Javascript 中的数字格式+转换?

python - 如何将函数结果传递给元组?

Python Spelling 替换包,如何将单词添加到字典中?

python - pyvnc2swf 不工作?输出时长 0 秒的视频

python - 权限错误 : [Errno 1] Operation not permitted: '/Users/<local_path>/venv/pyvenv.cfg'

algorithm - 大量数字的最有效排序算法

list - Lisp : (A (B C)), 为什么 1 个列表和 1 个原子?

c# - 根据分组删除列表中除 1 个对象以外的所有对象