如何使用列表理解从列表中删除重复项? [英] How to remove duplicate items from a list using list comprehension?

查看:80
本文介绍了如何使用列表理解从列表中删除重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用列表理解功能从列表中删除重复项?我有以下代码:

How to remove duplicate items from a list using list comprehension? I have following code:

a = [1, 2, 3, 3, 5, 9, 6, 2, 8, 5, 2, 3, 5, 7, 3, 5, 8]
b = []
b = [item for item in a if item not in b]

但是它不起作用,只是产生相同的列表.为什么它会产生相同的列表?

but it doesn't work, just produces identical list. Why its producing an identical list?

推荐答案

它正在生成与b相同的列表,在运行时不包含任何元素. 您想要什么:

It's producing an identical list as b contains no elements at run-time. What you'd want it this:

>>> a = [1, 2, 3, 3, 5, 9, 6, 2, 8, 5, 2, 3, 5, 7, 3, 5, 8]
>>> b = []
>>> [b.append(item) for item in a if item not in b]
[None, None, None, None, None, None, None, None]
>>> b
[1, 2, 3, 5, 9, 6, 8, 7]

这篇关于如何使用列表理解从列表中删除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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