列表理解不起作用[重复]

2024-02-04

我想将一个列表中的唯一项目放入另一个列表中,即消除重复的项目。当我用更长的方法来做时,我能够做到这一点,例如。

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

有人可以帮助理解列表理解中出了什么问题吗?

提前致谢 乌梅什


列表推导式提供了一种创建列表的简洁方法。常见的 应用程序将创建新列表,其中每个元素都是以下结果的结果 某些操作应用于另一个序列的每个成员或 可迭代,或者创建满足 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]

Notice:

append()回报None如果插入操作成功。

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

>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']
>>> list(set(a))
['and', 'sun', 'is', 'It', 'the', 'east', 'Juliet']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

列表理解不起作用[重复] 的相关文章

随机推荐