【发布时间】:2020-09-10 07:01:57
【问题描述】:
我想将一个列表中的唯一项放到另一个列表中,即消除重复项。例如,当我通过更长的方法执行此操作时,我可以做到这一点。
>>>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”
>>> new_list = []
>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']
>>> new_list = [new_list.append(word) for word in a if word not in new_list]
有人可以帮助理解列表理解中出了什么问题。
提前致谢 乌梅什
【问题讨论】:
-
append返回None,这就是添加到列表中的内容。我认为您需要查看列表推导。 -
我想你的意思是
if word not in new_list,而不是if word not in a。
标签: python for-loop list-comprehension