使用列表理解从列表中删除单词

2024-10-01 07:25:32 发布

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

我试图从列表中删除不必要的单词(an,a,the)

Test = ['a', 'an', 'the', 'love']
unWantedWords = ['a', 'an', 'the']
RD1 = [x for x in Test if x != unWantedWords]
print(RD1)
output ->['a', 'an', 'the', 'love']

这是怎么回事?


Tags: theintestan列表foroutputif
3条回答
RD1 = [x for x in Test if x not in unWantedWords]

unWantedWords是一个数组,你用一个数组来表示你的单词,这就是它不起作用的原因。在

问题是您将值x与整个列表unWantedWords进行比较。在

RD1 = [x for x in Test if x != unWantedWords]

更换!=不在检查x是否。。。不在里面!在

^{pr2}$

如果你不介意的话:

  1. 删除重复项
  2. 保持原有秩序

您可以简单地使用'set'(这里是核心算法):

>>> Test = ['a', 'an', 'the', 'love']
>>> unWantedWords = ['a', 'an', 'the']
>>> print set(Test) - set(unWantedWords)
set(['love'])

>>> print list(set(Test) - set(unWantedWords))
['love']

这具有优化复杂度的优势。在

当然,您可以包装此代码以保持重复和顺序。。。在

相关问题 更多 >