关于python:列表理解不起作用

List comprehension not working

本问题已经有最佳答案,请猛点这里访问。

我想把唯一的项目从一个列表放到另一个列表,即消除重复的项目。当我用更长的方法来做的时候,我就能够做到,比如说。

1
2
3
4
5
6
7
8
9
>>>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"。

1
2
3
>>> 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]

有人能帮你理解清单上的错误吗?

提前谢谢乌梅


List comprehensions provide a concise way to create lists. Common
applications are to make new lists where each element is the result of
some operations applied to each member of another sequence or
iterable, or to create a subsequence of those elements that satisfy a
certain condition.

也许你可以试试这个:

1
2
3
4
5
6
7
>>> 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删除重复项:

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


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

1
2
3
list(set(a))
# returns:
# ['It', 'is', 'east', 'and', 'the', 'sun', 'Juliet']

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

1
2
3
4
new_list = []
for word in a:
    if not a in new_list:
        new_list.append(word)