Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
55 views
in Technique[技术] by (71.8m points)

How to find duplicate elements in array using for loop in Python?

I have a list with duplicate elements:

 list_a=[1,2,3,5,6,7,5,2]

 tmp=[]

 for i in list_a:
     if tmp.__contains__(i):
         print i
     else:
         tmp.append(i)

I have used the above code to find the duplicate elements in the list_a. I don't want to remove the elements from list.

But I want to use for loop here. Normally C/C++ we use like this I guess:

 for (int i=0;i<=list_a.length;i++)
     for (int j=i+1;j<=list_a.length;j++)
         if (list_a[i]==list_a[j])
             print list_a[i]

how do we use like this in Python?

for i in list_a:
    for j in list_a[1:]:
    ....

I tried the above code. But it gets solution wrong. I don't know how to increase the value for j.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just for information, In python 2.7+, we can use Counter

import collections

x=[1, 2, 3, 5, 6, 7, 5, 2]

>>> x
[1, 2, 3, 5, 6, 7, 5, 2]

>>> y=collections.Counter(x)
>>> y
Counter({2: 2, 5: 2, 1: 1, 3: 1, 6: 1, 7: 1})

Unique List

>>> list(y)
[1, 2, 3, 5, 6, 7]

Items found more than 1 time

>>> [i for i in y if y[i]>1]
[2, 5]

Items found only one time

>>> [i for i in y if y[i]==1]
[1, 3, 6, 7]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...