Is it faster to union sets or check the whole list for a duplicate?

前端 未结 4 1544
攒了一身酷
攒了一身酷 2021-02-06 01:18

Sorry for the poorly worded title but I asked a question earlier about getting a unique list of items from two lists. People told me to make the list -> sets and then union.

4条回答
  •  伪装坚强ぢ
    2021-02-06 01:44

    as you can see extending one list by another end then remove duplicates by making set is the fastest way(at least in python;))

    >>> def foo():
    ...     """
    ...     extending one list by another end then remove duplicates by making set
    ...     """
    ...     l1 = range(200)
    ...     l2 = range(150, 250)
    ...     l1.extend(l2)
    ...     set(l1)
    ... 
    >>> def bar():
    ...     """
    ...     checking if element is on one list end adding it only if not
    ...     """
    ...     l1 = range(200)
    ...     l2 = range(150, 250)
    ...     for elem in l2:
    ...             if elem not in l1:
    ...                     l1.append(elem)
    ... 
    >>> def baz():
    ...     """
    ...     making sets from both lists and then union from them
    ...     """
    ...     l1 = range(200)
    ...     l2 = range(150, 250)
    ...     set(l1) | set(l2)
    ... 
    >>> from timeit import Timer
    >>> Timer(foo).timeit(10000)
    0.265153169631958
    >>> Timer(bar).timeit(10000)
    7.921358108520508
    >>> Timer(baz).timeit(10000)
    0.3845551013946533
    >>> 
    

提交回复
热议问题