将重复的列表对象添加到列表中

时间:2015-09-08 13:09:23

标签: python

我有一个对象列表,我需要迭代并将所有重复项或更多内容添加到另一个列表中并返回该列表。

list_in = ["a", "b", "b", "c", "d", "d", "d", "e"]
list_out = ["b", "b", "d", "d", "d"]

实现这一目标的最pythonic方式是什么,我尝试使用索引,但没有成功。

以下是我对此问题的初稿,但这绝不会增加。 如何使用索引实现这一点?

def find_dups(a):
    for i, item in enumerate(a)+1:
        j = i
        for j, item_b in enumerate(a)+1:
            if a[i] == a[j+1]:
                list_dups.append(a[i])
                list_dups.append(a[j+1])
                #break
                #print a[i], a[i+1]
    return list_dup

1 个答案:

答案 0 :(得分:1)

您应该使用list comprehension

list_out = [x for x in list_in if list_in.count(x) > 1]