【问题标题】:List comprehension not working [duplicate]列表理解不起作用[重复]
【发布时间】: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


【解决方案1】:

列表推导式提供了一种创建列表的简洁方式。常见的 应用程序将创建新列表,其中每个元素都是 应用于另一个序列的每个成员的一些操作或 可迭代,或创建满足 a 的那些元素的子序列 一定的条件。

也许你可以试试这个:

>>> 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']

【讨论】:

  • 快速回答。我正在写几乎相同的东西。 +1
【解决方案2】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    相关资源
    最近更新 更多