Skip to main content
 首页 » 编程设计

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

2025年05月04日11cyq1162

我需要一种方法来快速返回两个大列表之间的差异数。每个列表项的内容为 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