Remove all the elements that occur in one list from another

后端 未结 7 704
旧巷少年郎
旧巷少年郎 2020-11-21 23:45

Let\'s say I have two lists, l1 and l2. I want to perform l1 - l2, which returns all elements of l1 not in l2

相关标签:
7条回答
  • 2020-11-22 00:30

    Use the Python set type. That would be the most Pythonic. :)

    Also, since it's native, it should be the most optimized method too.

    See:

    http://docs.python.org/library/stdtypes.html#set

    http://docs.python.org/library/sets.htm (for older python)

    # Using Python 2.7 set literal format.
    # Otherwise, use: l1 = set([1,2,6,8])
    #
    l1 = {1,2,6,8}
    l2 = {2,3,5,8}
    l3 = l1 - l2
    
    0 讨论(0)
提交回复
热议问题