如何删除列表中的重复值? [英] How to delete duplicate values in a list?

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

问题描述

可能重复:
如何从中删除重复项保留顺序的同时用Python创建一个列表?

Possible Duplicate:
How do you remove duplicates from a list in Python whilst preserving order?

让我们考虑一下该列表:

Let us consider the list:

x = ['a', 'b', 'c', 'c', 'a', 'd', 'z', 'z']

我想删除这些重复的值list-x,并希望结果为:

I want to delete these duplicate values list-x and want the result as:

y = ['a', 'b', 'c', 'd', 'z']

推荐答案

如果订购无关紧要,请使用一组:

If ordering doesn't matter, use a set:

>>> list(set(['a', 'b', 'c', 'c', 'a', 'd', 'p', 'p']))
['a', 'p', 'c', 'b', 'd']

如果要订购 很重要,请使用 OrderedDict :

If ordering does matter, use an OrderedDict:

>>> from collections import OrderedDict 
>>> OrderedDict.fromkeys(['a', 'b', 'c', 'c', 'a', 'd', 'p', 'p']).keys()
['a', 'b', 'c', 'd', 'p']

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

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