Elegant way to compare sequences

前端 未结 8 1913
死守一世寂寞
死守一世寂寞 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:33

    You can determine the equality of any two iterables (strings, tuples, lists, even custom sequences) without creating and storing duplicate lists by using the following:

    all(x == y for x, y in itertools.izip_longest(a, b))
    

    Note that if the two iterables are not the same length, the shorter one will be padded with Nones. In other words, it will consider [1, 2, None] to be equal to (1, 2).

    Edit: As Kamil points out in the comments, izip_longest is only available in Python 2.6. However, the docs for the function also provide an alternate implementation which should work all the way back to 2.3.

    Edit 2: After testing on a few different machines, it looks like this is only faster than list(a) == list(b) in certain circumstances, which I can't isolate. Most of the time, it takes about seven times as long. However, I also found tuple(a) == tuple(b) to be consistently at least twice as fast as the list version.

提交回复
热议问题