Identify duplicate values in a list in Python

前端 未结 12 1908
渐次进展
渐次进展 2020-11-29 06:31

Is it possible to get which values are duplicates in a list using python?

I have a list of items:

    mylist = [20, 30, 25, 20]

I k

12条回答
  •  爱一瞬间的悲伤
    2020-11-29 07:03

    I tried below code to find duplicate values from list

    1) create a set of duplicate list

    2) Iterated through set by looking in duplicate list.

    glist=[1, 2, 3, "one", 5, 6, 1, "one"]
    x=set(glist)
    dup=[]
    for c in x:
        if(glist.count(c)>1):
            dup.append(c)
    print(dup)
    

    OUTPUT

    [1, 'one']

    Now get the all index for duplicate element

    glist=[1, 2, 3, "one", 5, 6, 1, "one"]
    x=set(glist)
    dup=[]
    for c in x:
        if(glist.count(c)>1):
            indices = [i for i, x in enumerate(glist) if x == c]
            dup.append((c,indices))
    print(dup)
    

    OUTPUT

    [(1, [0, 6]), ('one', [3, 7])]

    Hope this helps someone

提交回复
热议问题