什么在python中更有效 - 比较列表或字符串?

时间:2014-01-28 03:45:15

标签: python python-2.7

检查['a','b','c'] == ['a','b','c']'abc' =='abc'是否存在差异?

我不希望有,但想要仔细检查。

2 个答案:

答案 0 :(得分:2)

以下是使用timeit.timeit比较两种方法的速度的时间测试:

>>> from timeit import timeit
>>> list1 = ['a','b','c']
>>> list2 = ['x','y','z']
>>> timeit("list1 == list2", "from __main__ import list1, list2")
0.31944255484984296
>>> str1 = "abc"
>>> str2 = "xyz"
>>> timeit("str1 == str2", "from __main__ import str1, str2")
0.2439259738318924
>>>

如您所见,比较两个字符串比比较两个字符串要快一些。出于这个原因,请参阅@ user2864740的comment。 :)

答案 1 :(得分:1)

随着序列变大,字符串优势似乎会增加:

from timeit import timeit

for p in range(4):
    N = 10 ** p
    list1 = list(range(10)) * N
    list2 = list(list1)
    list2[-1] = 0
    str1 = ''.join(map(str, list1))
    str2 = ''.join(map(str, list2))

    # Sequences are equal except for their last element.
    # And everything is the same length.
    assert list1[:-1] == list2[:-1]
    assert str1[:-1]  == str2[:-1]
    assert list1      != list2
    assert str1       != str2
    assert len(list1) == len(list2)
    assert len(str1)  == len(str2)
    assert len(list1) == len(str1)

    a = timeit("list1 == list2", "from __main__ import list1, list2")
    b = timeit("str1 == str2", "from __main__ import str1, str2")
    print 'Length:', N * 10
    print '  list:  ', a
    print '  str:   ', b
    print '  ratio: ', a / b

一些结果:

Length: 10
  list:   0.0885802666801
  str:    0.0493016279308
  ratio:  1.79670064454
Length: 100
  list:   0.33228903865
  str:    0.0540730467332
  ratio:  6.14518801372
Length: 1000
  list:   2.78192754261
  str:    0.122594386356
  ratio:  22.6921282882
Length: 10000
  list:   26.8981546711
  str:    0.78435279802
  ratio:  34.2934387931