列表理解不起作用

2024-04-24 11:10:45 发布

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

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

>>>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”

^{pr2}$

有人能帮我理解一下清单理解中出了什么问题吗。在

提前谢谢 乌梅什


Tags: andthe项目方法in列表newfor
2条回答

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

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

如果顺序很重要,请尝试:

^{pr2}$

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.

也许你可以试试这个:

>>> 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删除重复项:

^{pr2}$

相关问题 更多 >