从列表中删除所有实例

2024-10-01 15:36:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从列表中删除所有单词实例。我搜索了一下,几乎所有的答案都与下面的代码相似,但我无法让它工作。列表只返回相同的列表,不删除任何单词。对于最后的print函数,如果我手动输入“and”之类的单词,而不是参数,那么它会工作,因此我假设它与“remove_words”列表有关

我正在使用vscode并导入了一个文本文件,其中包含一些段落

myFile = open("mytext.txt")

remove_words = ["and", "a", "to", "the", "if", "is", "it", "of"]

mylist = myFile.read().lower()
newlist = mylist.split(" ")

def remove_items(thelist, item):
    final_list = [i for i in thelist if i != item]
    return final_list

print(remove_items(newlist, remove_words))

Tags: and列表ifitemsitem单词myfileremove
3条回答

不要使用“!=”而是尝试“不在”。希望能奏效

您的问题是remove_words是一个字符串列表,而remove_items需要一个字符串。如果不想更改remove_items,则必须将remove_words中的每个项目分别传递给它:

for word in remove_words:
    newlist = remove_items(newlist, word)
print(newlist)

但是,正如其他人指出并给出的示例,如果您更改了remove_items,您可以让它接受要删除的单词列表,从而简化代码

您将remove_words作为item参数传递,这意味着您传递的是一个列表而不是一个单词

相关问题 更多 >

    热门问题