Remove multiple items from a Python list in just one statement

前端 未结 7 1546
逝去的感伤
逝去的感伤 2020-12-02 06:28

In python, I know how to remove items from a list.

item_list = [\'item\', 5, \'foo\', 3.14, True]
item_list.remove(\'item\')
item_list.remove(5)
7条回答
  •  甜味超标
    2020-12-02 06:52

    I'm reposting my answer from here because I saw it also fits in here. It allows removing multiple values or removing only duplicates of these values and returns either a new list or modifies the given list in place.


    def removed(items, original_list, only_duplicates=False, inplace=False):
        """By default removes given items from original_list and returns
        a new list. Optionally only removes duplicates of `items` or modifies
        given list in place.
        """
        if not hasattr(items, '__iter__') or isinstance(items, str):
            items = [items]
    
        if only_duplicates:
            result = []
            for item in original_list:
                if item not in items or item not in result:
                    result.append(item)
        else:
            result = [item for item in original_list if item not in items]
    
        if inplace:
            original_list[:] = result
        else:
            return result
    

    Docstring extension:

    """
    Examples:
    ---------
    
        >>>li1 = [1, 2, 3, 4, 4, 5, 5]
        >>>removed(4, li1)
           [1, 2, 3, 5, 5]
        >>>removed((4,5), li1)
           [1, 2, 3]
        >>>removed((4,5), li1, only_duplicates=True)
           [1, 2, 3, 4, 5]
    
        # remove all duplicates by passing original_list also to `items`.:
        >>>removed(li1, li1, only_duplicates=True)
          [1, 2, 3, 4, 5]
    
        # inplace:
        >>>removed((4,5), li1, only_duplicates=True, inplace=True)
        >>>li1
            [1, 2, 3, 4, 5]
    
        >>>li2 =['abc', 'def', 'def', 'ghi', 'ghi']
        >>>removed(('def', 'ghi'), li2, only_duplicates=True, inplace=True)
        >>>li2
            ['abc', 'def', 'ghi']
    """
    

    You should be clear about what you really want to do, modify an existing list, or make a new list with the specific items missing. It's important to make that distinction in case you have a second reference pointing to the existing list. If you have, for example...

    li1 = [1, 2, 3, 4, 4, 5, 5]
    li2 = li1
    # then rebind li1 to the new list without the value 4
    li1 = removed(4, li1)
    # you end up with two separate lists where li2 is still pointing to the 
    # original
    li2
    # [1, 2, 3, 4, 4, 5, 5]
    li1
    # [1, 2, 3, 5, 5]
    

    This may or may not be the behaviour you want.

提交回复
热议问题