从列表中删除某个单词

时间:2017-11-22 15:20:20

标签: python

我不得不将物品放入清单,但因为我不知道有多少物品我必须将清单设置为

matching_words=["none"]*100

一旦添加了所有单词,我就希望删除剩余的“无”,因此列表只有添加的单词数量。如何才能做到这一点。我试过这个

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

此返回

None

2 个答案:

答案 0 :(得分:4)

您应该已经开始使用空列表并附加了项目:

remove

另外,您只需知道print(matching_words) matching_words.remove('bar') print(matching_words) 方法:

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

示例输出:

{{1}}

答案 1 :(得分:0)

当你需要定义列表长度时以及不需要时,我想解释一些事情。

  

首先,您不需要在开头定义列表长度   一般情况:

您可以这样做:

#Just for example

new_list=[]

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

print(new_list)

输出:

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

是的,当你有另一个列表时,你需要定义一个空列表   像这样的索引项目:

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']

在这个程序中,我们必须按照index_list显示整数的顺序插入chracter,所以如果我们在之前没有定义列表的情况下尝试,你可以看到我们在索引4处插入第一个chr,而不是那里。

在你的情况下,如果你有第二种情况,那么试试这个删除其余的没有:

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

否则,如果你应该先处理案件。