Python:从2个大数组计算事件

Led*_*Led 3 python

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

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))
Run Code Online (Sandbox Code Playgroud)

在处理小阵列大小时它是可以的,但是当阵列大小增加时(100万array_1和100万array_2)会遇到困难.有没有更好的方法来解决这个问题?

抱歉混淆,我稍微更新了一下这个问题.

Meg*_*Ing 5

注意:@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))
Run Code Online (Sandbox Code Playgroud)