请帮助(我知道这是一个愚蠢的问题):
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列表中出现一次以上的元素
发布评论