Elegant way to compare sequences

前端 未结 8 1926
死守一世寂寞
死守一世寂寞 2021-02-05 20:10

Does python provide an elegant way to check for \"equality\" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:

8条回答
  •  礼貌的吻别
    2021-02-05 20:36

    Apart from the extra memory used by creating temporary lists/tuples, those answers will lose out to short circuiting generator solutions for large sequences when the inequality occurs early in the sequences

    from itertools import starmap, izip
    from operator import eq
    all(starmap(eq, izip(x, y)))
    

    or more concisely

    from itertools import imap
    from operator import eq
    all(imap(eq, x, y))
    

    some benchmarks from ipython

    x=range(1000)
    y=range(1000); y[10]=0
    
    timeit tuple(x) == tuple(y)
    100000 loops, best of 3: 16.9 us per loop
    
    timeit all(imap(eq, x, y))
    100000 loops, best of 3: 2.86 us per loop
    

提交回复
热议问题