首页 > 解决方案 > Python:从 2 个大数组中计算出现次数

问题描述

我有以下脚本计算从一个数组到另一个数组的值的出现

array_1 = [1,2,0,5,7,0]
array_2 = [1,0,1,1,9,6]
# on array 2 there are 3 occurrence of 1, and 1 occurrence of zero, but because there is another zero at array_1 add 1 more. 3+2 = 5

for r in array_1:
     total_count = total_count + array_2.count(r)

print("total sum: {0}".format(total_count))

处理小数组大小时可以,但是当数组大小增加时(100 万array_1和 100 万array_2)会很困难。有没有更好的方法来解决这个问题?

很抱歉造成混乱,我稍微更新了这个问题。

标签: python

解决方案


注意:@Netwave 的答案快了五倍。

您可以使用collections.Counter. 它更快,因为它只迭代列表中的一个。

from collections import Counter

array_1 = [1,2,0,5,7]
array_2 = [1,0,1,1,9]

c = Counter(array_1)
total_count = sum(c[x] for x in array_2)

print("total sum: {0}".format(total_count))

推荐阅读