python - 比较两个 1's & 0' s 的大列表并返回差异计数/百分比的最快方法是什么?

标签 python performance list compare

我需要一种方法来快速返回两个大列表之间的差异数。每个列表项的内容为 1 或 0(单个整数),每个列表中的项数始终为 307200。

这是我当前代码的示例:

list1 = <list1> # should be a list of integers containing 1's or 0's
list2 = <list2> # same rule as above, in a slightly different order

diffCount = 0
for index, item in enumerate(list1):
    if item != list2[index]:
        diffCount += 1

percent = float(diffCount) / float(307200)

上面的方法有效,但对我来说太慢了。我想知道的是,是否有更快的方法来获取列表之间的差异数量,或者不同项目的百分比?

我已经查看了该站点上的一些类似主题,但它们的工作方式似乎都与我想要的略有不同,而且 set() 示例似乎不适合我的目的。 :P

最佳答案

如果使用 NumPy,您至少可以获得 10 倍的加速数组而不是列表。

import random
import time
import numpy as np
list1 = [random.choice((0,1)) for x in xrange(307200)]
list2 = [random.choice((0,1)) for x in xrange(307200)]
a1 = np.array(list1)
a2 = np.array(list2)

def foo1():
    start = time.clock()
    counter = 0
    for i in xrange(307200):
        if list1[i] != list2[i]:
            counter += 1
    print "%d, %f" % (counter, time.clock()-start)

def foo2():
    start = time.clock()
    ct = np.sum(a1!=a2)
    print "%d, %f" % (ct, time.clock()-start)
    
foo1() #153490, 0.096215
foo2() #153490, 0.010224

关于python - 比较两个 1's & 0' s 的大列表并返回差异计数/百分比的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5534500/

相关文章:

python - 使用 Dataframe.Groupby 对行进行分组,但将其他字段与 Grouper 中提到的列分开

python - Bash 别名 --> Python 2.7 到 Python 3.3

php - 多数据库查询感知性能

SQL 查询 - 当我们在 where 子句中使用主键时更新/删除语句的性能

python - 将列表中的可能值添加到 groupby 结果

python - 如何将 1 个函数中的字符串输入到另外 2 个函数中,并在 python 中打印它?

python - 在 Python 中生成 Chebyshev 多项式的系数

performance - Joomla与CodeIgniter/YII

list - 如何仅使用 cons 和空列表创建列表? Racket

algorithm - 将真/假向量分解成它的部分