2024-10-01 07:25:32 发布
网友
我试图从列表中删除不必要的单词(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']
这是怎么回事?
RD1 = [x for x in Test if x not in unWantedWords]
unWantedWords是一个数组,你用一个数组来表示你的单词,这就是它不起作用的原因。在
问题是您将值x与整个列表unWantedWords进行比较。在
RD1 = [x for x in Test if x != unWantedWords]
更换!=不在检查x是否。。。不在里面!在
如果你不介意的话:
您可以简单地使用'set'(这里是核心算法):
>>> Test = ['a', 'an', 'the', 'love'] >>> unWantedWords = ['a', 'an', 'the'] >>> print set(Test) - set(unWantedWords) set(['love']) >>> print list(set(Test) - set(unWantedWords)) ['love']
这具有优化复杂度的优势。在
当然,您可以包装此代码以保持重复和顺序。。。在
unWantedWords是一个数组,你用一个数组来表示你的单词,这就是它不起作用的原因。在
问题是您将值x与整个列表unWantedWords进行比较。在
更换!=不在检查x是否。。。不在里面!在
^{pr2}$如果你不介意的话:
您可以简单地使用'set'(这里是核心算法):
这具有优化复杂度的优势。在
当然,您可以包装此代码以保持重复和顺序。。。在
相关问题 更多 >
编程相关推荐