Elegant way to compare sequences

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

    I think it's a good idea to special case when both sequences are type list. Comparing two lists is faster (and more memory efficient) than converting both to tuples.

    In the case that either a or b are not lists, they are both converted to tuple. There is no overhead if one or both are already tuples, as tuple() just returns a reference to the original object in that case.

    def comp(a, b):
        if len(a) != len(b):
            return False
        if type(a) == type(b) == list:
            return a == b
        a = tuple(a)
        b = tuple(b)
        return a == b
    

提交回复
热议问题