列表理解不起作用 [英] List comprehension not working

查看:58
本文介绍了列表理解不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个列表中的唯一项放到另一个列表中,即消除重复项.当我使用更长的方法进行操作时,例如可以看到它.

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

但是当尝试在一行中使用列表理解来完成此操作时,每次迭代都会返回值"None"

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.

预先感谢Umesh

推荐答案

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

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)

这篇关于列表理解不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆