在Python列表中出现一次以上的元素

编程入门 行业动态 更新时间:2024-10-10 20:15:41
本文介绍了在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列表中出现一次以上的元素

本文发布于:2023-11-30 22:05:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651611.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   列表中   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!