如何从列表中删除特定项目?

1 python loops for-loop list

我正在尝试从菜单上的给定选项中删除垃圾邮件,我的for循环不起作用。

menu = [
    ["egg", "bacon"],
    ["egg", "sausage", "bacon"],
    ["egg", "spam"],
    ["egg", "bacon", "spam"],
    ["egg", "bacon", "sausage", "spam"],
    ["spam", "bacon", "sausage", "spam"],
    ["spam", "sausage", "spam", "bacon", "spam", "tomato", 
    "spam"],
    ["spam", "egg", "spam", "spam", "bacon", "spam"],
]

for choice in menu:
    if "spam" in choice:
        remove("spam")
        print(choice)
Run Code Online (Sandbox Code Playgroud)

Kra*_*las 7

正如@h4z4 所述,remove未定义。尝试

for choice in menu:
    if "spam" in choice:
        choice.remove("spam")
        print(choice)
Run Code Online (Sandbox Code Playgroud)

但是,remove仅删除第一次出现。要删除所有出现,请尝试:

for choice in menu:
    if "spam" in choice:
        choice = [item for item in choice if item != "spam"]
        print(choice)
Run Code Online (Sandbox Code Playgroud)


And*_*ely 5

要从子列表中删除所有“垃圾邮件”,请使用列表理解:

menu = [
    ["egg", "bacon"],
    ["egg", "sausage", "bacon"],
    ["egg", "spam"],
    ["egg", "bacon", "spam"],
    ["egg", "bacon", "sausage", "spam"],
    ["spam", "bacon", "sausage", "spam"],
    ["spam", "sausage", "spam", "bacon", "spam", "tomato", "spam"],
    ["spam", "egg", "spam", "spam", "bacon", "spam"],
]

menu = [[val for val in subl if val != "spam"] for subl in menu]
print(menu)
Run Code Online (Sandbox Code Playgroud)

印刷:

[['egg', 'bacon'], 
 ['egg', 'sausage', 'bacon'], 
 ['egg'], 
 ['egg', 'bacon'], 
 ['egg', 'bacon', 'sausage'], 
 ['bacon', 'sausage'], 
 ['sausage', 'bacon', 'tomato'], 
 ['egg', 'bacon']]
Run Code Online (Sandbox Code Playgroud)