Python: Determine if an unsorted list is contained in a 'list of lists', regardless of the order to the elements

前端 未结 4 427
鱼传尺愫
鱼传尺愫 2021-01-29 00:27

I have a similar question to this question: Determine if 2 lists have the same elements, regardless of order?

What is the best/quickest way to determine whether an unsor

4条回答
  •  北海茫月
    2021-01-29 00:52

    This algorithm appears to be slightly faster:

    l1 = [3, 4, 1, 2, 3]
    l2 = [4, 2, 3, 3, 1]
    same = True
    for i in l1:
        if i not in l2:
            same = False
            break
    

    For 1000000 loops, this takes 1.25399184227 sec on my computer, whilst

    same = sorted(l1) == sorted(l2)
    

    takes 1.9238319397 sec.

提交回复
热议问题