Python 列表理解不起作用

Python 列表理解不起作用,python,for-loop,list-comprehension,Python,For Loop,List Comprehension,我想将唯一项从一个列表放到另一个列表中,即消除重复项。当我用更长的方法做的时候,我能做到,比如看 >>>new_list = [] >>>a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun'] >>> for word in a: if word not in a: new_list.append(word) >>>

我想将唯一项从一个列表放到另一个列表中,即消除重复项。当我用更长的方法做的时候,我能做到,比如看

>>>new_list = []
>>>a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']

>>> for word in a:
    if word not in a:
        new_list.append(word)

>>> new_list
['It', 'is', 'the', 'east', 'and', 'Juliet', 'sun']
但是,当尝试在一行中使用列表理解来完成此任务时,每次迭代都会返回值“None”

请有人帮助理解列表中的错误

提前谢谢 乌梅什

列表理解提供了创建列表的简明方法。普通的 应用程序将创建新的列表,其中每个元素都是 应用于另一序列或序列的每个成员的某些操作 iterable,或创建满足 一定条件

也许你可以试试这个:

>>> new_list = []
>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']
>>> unused=[new_list.append(word) for word in a if word not in new_list]
>>> new_list
['It', 'is', 'the', 'east', 'and', 'Juliet', 'sun']
>>> unused
[None, None, None, None, None, None, None]
注意:

append()
如果插入的操作成功,则返回
None

另一种方法是,您可以尝试使用
set
删除重复项:

>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']
>>> list(set(a))
['and', 'sun', 'is', 'It', 'the', 'east', 'Juliet']

如果需要唯一的单词列表,可以使用
set()

如果订单很重要,请尝试:

new_list = []
for word in a:
    if not a in new_list:
        new_list.append(word)

append
返回
None
,这就是添加到列表中的内容。我想你需要检查一下列表的理解。我想你的意思是,如果单词不在新的列表中,你的意思是
,如果单词不在新的列表中,你的意思是
。快速回答。我写的都差不多+1.
list(set(a))
# returns:
# ['It', 'is', 'east', 'and', 'the', 'sun', 'Juliet']
new_list = []
for word in a:
    if not a in new_list:
        new_list.append(word)