How to efficiently compare two unordered lists (not sets) in Python?

前端 未结 10 1106
刺人心
刺人心 2020-11-22 15:00
a = [1, 2, 3, 1, 2, 3]
b = [3, 2, 1, 3, 2, 1]

a & b should be considered equal, because they have exactly the same elements, only in different

10条回答
  •  时光取名叫无心
    2020-11-22 15:33

    Let a,b lists

    def ass_equal(a,b):
    try:
        map(lambda x: a.pop(a.index(x)), b) # try to remove all the elements of b from a, on fail, throw exception
        if len(a) == 0: # if a is empty, means that b has removed them all
            return True 
    except:
        return False # b failed to remove some items from a
    

    No need to make them hashable or sort them.

提交回复
热议问题