Skip to main content
 首页 » 编程设计

python之我该如何解决这个 list.remove() 错误

2025年05月04日12soundcode

<分区>

我有两个输入(文本 - 一个字符串,L1 - 要排除的字符串列表)。

我已将“文本”转换为列表并提取每个单词并使用以下代码将其放入列表中:

Text=list(Text.split()) 

现在我必须从这个“文本”列表中删除 L1 列表中的单词。 为此,我使用了以下代码:

for x in Text: 
        if(x in L1): 
            Text.remove(x) 
print(Text) 

输入:

Text = "jack and jill went to the market to buy bread and cheese cheese is jack favorite food" 
 
L1 = ["and","he","the","to","is"] 

期望的输出:

['jack', 'jill', 'went', 'market', 'buy', 'bread', 'cheese', 'cheese', 'jack', 'favorite', 'food']

实际输出:

['jack', 'jill', 'went', 'the', 'market', 'buy', 'bread', 'cheese', 'cheese', 'jack', 'favorite', 'food']

请告诉我为什么 'the' 仍然出现在 'Text' 中?

我做错了什么? 我应该怎么做才能获得我想要的结果?