从列表中删除项目(如果存在)

时间:2019-10-02 14:27:51

标签: python list function

如果列表中存在项目,我的代码将不会删除它们。

这是我正在使用的列表:[1, 2, 3, 4, 5, 6, 7, 8]

运行函数:remove_items_from_list(my_list, [1,5,6])

这是我期望的输出:[2, 3, 4, 7, 8]

但是我得到:[1, 2, 3, 4, 5, 6, 7, 8]

def remove_items_from_list(ordered_list, items_to_remove):
    if [items_to_remove] in ordered_list :
        ordered_list.remove([items_to_remove])
    return ordered_list

以下是我的说明: 此函数有两个参数:一个列表和要从列表中删除的数字列表。然后,此功能将检查该列表中是否存在这些项目,如果存在,则将其删除。

3 个答案:

答案 0 :(得分:1)

如果[items] in list检查以下内容:包含项列表的列表是该列表的元素。也就是说,您在问:[[1, 2, 3]]是列表的成员吗?可能不是。

您想要做的是遍历items_to_remove的元素,然后做您想做的事

for item in items_to_remove:
    if item in list:
        list.remove(item)

答案 1 :(得分:1)

尝试一下:

def remove_items_from_list(ordered_list, items_to_remove):
    return [i for i in ordered_list if not i in items_to_remove]

答案 2 :(得分:0)

blue_note提供的答案是正确的,但是更惯用的方法是通过列表理解来做到这一点,就像这样:

return [x for x in ordered_list if x not in items_to_remove]

请注意,这不会从原始列表中删除项目,而是返回不包含项目的新列表(如Bastian所指出的那样)。

编辑:Arkistarvh Kltzuonstev击败了我,但我仍然认为x not in ynot x in y更惯用。