python - 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
)会很困难。有没有更好的方法来解决这个问题?
很抱歉造成混乱,我稍微更新了这个问题。
解决方案
注意:@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))
推荐阅读
- python - pandas dataframe drop问题,要删除特定行吗?
- typescript - 如何通过 AWS Eventbridge 保存相关 ID
- php - 按钮软删除不起作用laravel 8
- reactjs - 如何通过 jest.mock 在反应中模拟一个类组件?
- excel - 从 excel 列表中获取电子邮件,然后编辑主题并将更新的邮件项目保存为 pdf
- javascript - 为什么我的 Accordion 关闭动画没有触发?它打开(有动画)但没有动画关闭
- node.js - REST API - 排除/包括软删除的项目
- sql - 日期格式:获取月份的最后一天和第一天-sql-DB2
- javascript - process.on('uncaughtException') 没有捕获 ECONNRESET
- css - 为什么 stylelint 会忽略 ignoreFiles 配置中的 js 文件?