在Python列表中出现一次以上的元素 [英] element that appear more that once in the list in Python

查看:105
本文介绍了在Python列表中出现一次以上的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助(我知道这是一个愚蠢的问题):

Please help (I know that it's a silly question):

我有一个列表d = [' ABA', ' AAB', ' BAA', ' BAA', ' AAB', ' ABA'].如何排除出现多次的元素?

I have a list d = [' ABA', ' AAB', ' BAA', ' BAA', ' AAB', ' ABA']. How can I exclude elements that appear more than once?

推荐答案

转换为集合然后再次返回:

Convert to a set then back again:

list(set(d))

如果顺序很重要,则可以通过记住原始索引的字典传递值.这种方法虽然可以表达为单个表达式,但要复杂得多:

If order matters, you can pass the values through a dict that remembers the original indices. This approach, while expressible as a single expression, is considerably more complicated:

[x for (i, x) in sorted((i, x) for (x, i) in dict((x, i) for (i, x) in reversed(list(enumerate(d)))).iteritems())]

当然,您不必使用理解力.对于此问题,可以使用一个相当简单的解决方案:

Of course, you don't have to use comprehensions. For this problem, a fairly simple solution is available:

a = []
for x in d:
    if x not in a:
        a.append(x)

请注意,两种保留顺序的解决方案都假定您要保留每个重复元素的第一次出现.

Note that both the order-preserving solutions assume that you want to keep the first occurrence of each duplicated element.

这篇关于在Python列表中出现一次以上的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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