Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python在列表中列出重复值的索引_Python_List_Indexing_Duplicates_List Comprehension - Fatal编程技术网

使用Python在列表中列出重复值的索引

使用Python在列表中列出重复值的索引,python,list,indexing,duplicates,list-comprehension,Python,List,Indexing,Duplicates,List Comprehension,我试图修改这个列出重复项的定义,以便它列出重复值的索引。另外,我希望它列出所有的重复项,这意味着a=[1,2,3,2,1,5,6,5,5,5]的结果将是重复的索引=[3,4,7,8,9],定义如下: def list_duplicates(seq): seen = set() seen_add = seen.add # adds all elements it doesn't know yet to seen and all other to seen_twice

我试图修改这个列出重复项的定义,以便它列出重复值的索引。另外,我希望它列出所有的重复项,这意味着a=[1,2,3,2,1,5,6,5,5,5]的结果将是重复的索引=[3,4,7,8,9],定义如下:

def list_duplicates(seq):
    seen = set()
    seen_add = seen.add
    # adds all elements it doesn't know yet to seen and all other to seen_twice
    seen_twice = set( x for x in seq if x in seen or seen_add(x) )
    # turn the set into a list (as requested)
    return list( seen_twice )

a = [1,2,3,2,1,5,6,5,5,5]
list_duplicates(a) # yields [1, 2, 5]
编辑:您可以在该函数中使用列表理解,如下所示

def list_duplicates(seq):
    seen = set()
    seen_add = seen.add
    return [idx for idx,item in enumerate(seq) if item in seen or seen_add(item)]

print list_duplicates([1, 2, 3, 2, 1, 5, 6, 5, 5, 5])
# [3, 4, 7, 8, 9]

列表理解以打印副本索引。它将列表切片到所选索引,如果项目已存在于切片列表中,则返回索引值

a= [1, 2, 3, 2, 1, 5, 6, 5, 5, 5]
result=[idx for idx, item in enumerate(a) if item in a[:idx]]
print result #[3, 4, 7, 8, 9]

与其他答案相比,您使用的是一组
seen
使成员资格测试快速?+1,因为它是最短且最清楚地表达规范的答案。
def list_duplicates_index(seq):
    return [i for (i,x) in enumerate(a) if x in list_duplicates(a)]
a= [1, 2, 3, 2, 1, 5, 6, 5, 5, 5]
result=[idx for idx, item in enumerate(a) if item in a[:idx]]
print result #[3, 4, 7, 8, 9]
def list_duplicates(seq):
    d = {}
    for i in seq:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    dups = []
    for i in d:
        if d[i] > 1:
            dups.append(i)
    lst = []
    for i in dups:
        l = []
        for index in range(len(seq)):
            if seq[index] == i:
                l.append(index)
        lst.append(l[1:])
    new = []
    for i in lst:
        for index in i:
            new.append(index)   
    return new