Elegant way to compare sequences

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

    It's probably not as efficient, but it looks funky:

    def cmpLists(a, b):
        return len(a) == len(b) and (False not in [a[i] == b[i] for i in range(0,len(a)])
    

    I don't know the "all" function that Ben mentioned, but perhaps you could use that instead of "False not in"

    0 讨论(0)
  • 2021-02-05 20:57

    This "functional" code should be fast and generic enough for all purposes.

    # python 2.6 ≤ x < 3.0
    import operator, itertools as it
    
    def seq_cmp(seqa, seqb):
        return all(it.starmap(operator.eq, it.izip_longest(seqa, seqb)))
    

    If on Python 2.5, use the definition for izip_longest from there.

    0 讨论(0)
提交回复
热议问题