看起来tuple(a) == tuple(b)是最好的选择。或者在它们经常有不同长度的情况下,可以使用带有先前len检查的元组比较。这确实会创建额外的列表,但除了对于真正巨大的列表可能会有问题以外,希望不会有太大问题。以下是我对各种建议的比较:
import timeit
tests = (
'''
a=b=[5]*100
''',
'''
a=[5]*100
b=[5]*3
''',
'''
a=b=(5,)*100
''',
'''
a=b="This on is a string" * 5
''',
'''
import array
a=b=array.array('B', "This on is a string" * 5)
'''
)
common = '''import itertools
def comp1(a, b):
if len(a) != len(b):
return False
for i, v in enumerate(a):
if v != b[i]:
return False
return True'''
for i, setup in enumerate(tests):
t1 = timeit.Timer("comp1(a, b)", setup + common)
t2 = timeit.Timer("all(x == y for x, y in itertools.izip_longest(a, b))", setup + common)
t3 = timeit.Timer("all([x == y for x, y in itertools.izip_longest(a, b)])", setup + common)
t4 = timeit.Timer("list(a) == list(b)", setup + common)
t5 = timeit.Timer("tuple(a) == tuple(b)", setup + common)
print '==test %d==' % i
print ' comp1: %g' % t1.timeit()
print ' all gen: %g' % t2.timeit()
print 'all list: %g' % t3.timeit()
print ' list: %g' % t4.timeit()
print ' tuple: %g\n' % t5.timeit()
以下是结果:
==test 0==
comp1: 27.8089
all gen: 31.1406
all list: 29.4887
list: 3.58438
tuple: 3.25859
==test 1==
comp1: 0.833313
all gen: 3.8026
all list: 33.5288
list: 1.90453
tuple: 1.74985
==test 2==
comp1: 30.606
all gen: 31.4755
all list: 29.5637
list: 3.56635
tuple: 1.60032
==test 3==
comp1: 33.3725
all gen: 35.3699
all list: 34.2619
list: 10.2443
tuple: 10.1124
==test 4==
comp1: 31.7014
all gen: 32.0051
all list: 31.0664
list: 8.35031
tuple: 8.16301
编辑:增加了几个测试。这是在一台搭载AMD 939 3800+和2GB内存的计算机上运行的。使用的操作系统是Linux 32位,Python版本为2.6.2。