Identify duplicate values in a list in Python

前端 未结 12 1885
渐次进展
渐次进展 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 06:43

    You should sort the list:

    mylist.sort()
    

    After this, iterate through it like this:

    doubles = []
    for i, elem in enumerate(mylist):
        if i != 0:
            if elem == old:
                doubles.append(elem)
                old = None
                continue
        old = elem
    
    0 讨论(0)
  • 2020-11-29 06:46

    The following list comprehension will yield the duplicate values:

    [x for x in mylist if mylist.count(x) >= 2]
    
    0 讨论(0)
  • 2020-11-29 06:46

    The following code will fetch you desired results with duplicate items and their index values.

      for i in set(mylist):
        if mylist.count(i) > 1:
             print(i, mylist.index(i))
    
    0 讨论(0)
  • 2020-11-29 06:49

    You can use list compression and set to reduce the complexity.

    my_list = [3, 5, 2, 1, 4, 4, 1]
    opt = [item for item in set(my_list) if my_list.count(item) > 1]
    
    0 讨论(0)
  • 2020-11-29 06:57

    You can print duplicate and Unqiue using below logic using list.

    def dup(x):
        duplicate = []
        unique = []
        for i in x:
            if i in unique:
                duplicate.append(i)
            else:
                unique.append(i)
        print("Duplicate values: ",duplicate)
        print("Unique Values: ",unique)
    
    list1 = [1, 2, 1, 3, 2, 5]
    dup(list1)
    
    0 讨论(0)
  • 2020-11-29 07:00
    m = len(mylist)
    for index,value in enumerate(mylist):
            for i in xrange(1,m):
                    if(index != i):
                        if (L[i] == L[index]):
                            print "Location %d and location %d has same list-entry:  %r" % (index,i,value)
    

    This has some redundancy that can be improved however.

    0 讨论(0)
提交回复
热议问题