AWa*_*inb 1 python performance compare list
我需要一种方法来快速返回两个大列表之间的差异数量.每个列表项的内容为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)
Run Code Online (Sandbox Code Playgroud)
上面的工作,但它对我的目的来说太慢了.我想知道的是,是否有更快的方法来获得列表之间的差异数量,或者不同的项目百分比?
我在这个网站上看了几个类似的线程,但它们似乎与我想要的工作略有不同,而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
Run Code Online (Sandbox Code Playgroud)