List comprehension not working [duplicate]

夙愿已清 提交于 2021-02-05 12:20:45

问题


I want to put the unique items from one list to another list, i.e eliminating duplicate items. When I do it by the longer method I am able to do it see for example.

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

But when try to accomplish this using list comprehension in a single line the each iteration returns value "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]

Can someone please help in understanding whats going wrong in the list comprehension.

Thanks in Advance Umesh


回答1:


If you want a unique list of words, you can use set().

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

If the order is important, try:

new_list = []
for word in a:
    if not a in new_list:
        new_list.append(word)



回答2:


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.

Maybe you can try this:

>>> 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() returns None if the inserted operation is successful.

Another way, you can try to use set to remove duplicate item:

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


来源:https://stackoverflow.com/questions/43152140/list-comprehension-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!