Remove multiple items from a Python list in just one statement

前端 未结 7 1544
逝去的感伤
逝去的感伤 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 06:47

    I don't know why everyone forgot to mention the amazing capability of sets in python. You can simply cast your list into a set and then remove whatever you want to remove in a simple expression like so:

    >>> item_list = ['item', 5, 'foo', 3.14, True]
    >>> item_list = set(item_list) - {'item', 5}
    >>> item_list
    {True, 3.14, 'foo'}
    >>> # you can cast it again in a list-from like so
    >>> item_list = list(item_list)
    >>> item_list
    [True, 3.14, 'foo']
    

提交回复
热议问题