从列表中删除某个单词

2024-04-29 09:25:31 发布

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

我不得不把项目放入一个列表中,但因为我不知道有多少项目,我不得不设置为列表

matching_words=["none"]*100

一旦所有的单词都被添加了,我就希望剩下的“none”被删除,这样列表就只和添加的单词数一样长。如何做到这一点。我试过了

newMatching_words=matching_words.remove("ABCDEFG")
print(newMatching_words)

他回来了

None

Tags: 项目none列表单词removewordsprintmatching
2条回答

您应该从一个空列表开始,并向其中添加以下项目:

matching_words = []

for word in source_of_words:
    matching_words.append(word)

print(matching_words)

另外,为了让您了解remove方法:

print(matching_words)

matching_words.remove('bar')

print(matching_words)

样本输出:

['foo', 'bar', 'baz']
['foo', 'baz']

当你需要定义列表长度和不需要的时候,我想解释一些事情

First, you don't need to define list length at the beginning in general case:

您可以简单地执行以下操作:

#Just for example

new_list=[]

for i in map(chr,range(97,101)):
    new_list.append(i)

print(new_list)

输出:

['a', 'b', 'c', 'd']

Yes you need to define a empty list when you have another list for index items like this:

matching_words=[None]*10

index_list=[4,3,1,2]

for i in zip(list(map(chr,range(97,101))),index_list):
    matching_words.insert(i[1],i[0])

print(matching_words)

输出:

[None, 'c', 'd', None, None, 'b', None, 'a', None, None, None, None, None, None]
['c', 'd', 'b', 'a']

在这个程序中,我们必须按索引列表显示整数的顺序插入chracter,所以如果我们不在之前定义list,那么正如你所看到的,我们在索引4处插入第一个chr,而索引4不在那里

在您的情况下,如果您有第二种情况,请尝试此操作以删除其余情况:

print([i for i in matching_words if i!='none'])

否则,如果你是第一个病例

相关问题 更多 >