# duplicates list重复元素位置 - 如何在Python中使用for循环在数组中查找重复元素？

## list找出重复元素 list中的index (13)

`````` 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)
``````

`````` 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]
``````

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

``````>>> lst = [1, 2, 3, 5, 6, 7, 5, 2]
>>> stats = {}
>>> for x in lst : # count occurrences of each letter:
...     stats[x] = stats.get(x, 0) + 1
>>> print stats
{1: 1, 2: 2, 3: 1, 5: 2, 6: 1, 7: 1} # filter letters appearing more than once:
>>> duplicates = [dup for (dup, i) in stats.items() if i > 1]
>>> print duplicates
``````

``````def getDuplicates(iterable):
"""
Take an iterable and return a generator yielding its duplicate items.
Items must be hashable.

e.g :

>>> sorted(list(getDuplicates([1, 2, 3, 5, 6, 7, 5, 2])))
[2, 5]
"""
stats = {}
for x in iterable :
stats[x] = stats.get(x, 0) + 1
return (dup for (dup, i) in stats.items() if i > 1)
``````

``````def getDuplicates(iterable):
"""
Take an iterable and return a generator yielding its duplicate items.
Items must be hashable.

e.g :

>>> sorted(list(getDuplicates([1, 2, 3, 5, 6, 7, 5, 2])))
[2, 5]
"""
try: # try using built-in set
found = set()
except NameError: # fallback on the sets module
from sets import Set
found = Set()

for x in iterable:
if x in found : # set is a collection that can't contain duplicate
yield x
found.add(x) # duplicate won't be added anyway
``````

``````import collections

def getDuplicates(iterable):
"""
Take an iterable and return a generator yielding its duplicate items.
Items must be hashable.

e.g :

>>> sorted(list(getDuplicates([1, 2, 3, 5, 6, 7, 5, 2])))
[2, 5]
"""
return (dup for (dup, i) in collections.counter(iterable).items() if i > 1)
``````

`tmp = list(set(list_a))`

``````for i in xrange(len(list_a)):
for j in xrange(i + 1, len(list_a)):
if list_a[i] == list_a[j]:
print "duplicate:", list_a[i]
``````

``````seen = set()
for n in list_a:
if n in seen:
print "duplicate:", n
else:
``````

``````import collections
items = collections.defaultdict(list)
for i, item in enumerate(list_a):
items[item].append(i)
for item, locs in items.iteritems():
if len(locs) > 1:
print "duplicates of", item, "at", locs
``````

``````if len(set(list_a)) != len(list_a):
print "duplicate"
``````

`````` pd.DataFrame(list_a, columns=["x"]).groupby('x').size().to_dict()
``````

``````import numpy as np
count,value = np.histogram(list_a,bins=np.hstack((np.unique(list_a),np.inf)))
print 'duplicate value(s) in list_a: ' + ', '.join([str(v) for v in value[count>1]])
``````

C ++

``````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]
``````

``````for i in range(0, len(list_a)):
for j in range(i + 1, len(list_a))
if list_a[i] == list_a[j]:
print list_a[i]
``````

c ++ for循环：

``````for(int x = start; x < end; ++x)
``````

Python等价物：

``````for x in range(start, end):
``````

``````def get_duplicates(arr):
dup_arr = arr[:]
for i in set(arr):
dup_arr.remove(i)
return list(set(dup_arr))

print get_duplicates([1,2,3,5,6,7,5,2])
[2, 5]

print get_duplicates([1,2,1,3,4,5,4,4,6,7,8,2])
[1, 2, 4]
``````

```import collections
l = [1, 2, 4, 1, 3, 3]
d = collections.defaultdict(int)
for x in l:
d[x] += 1
print [k for k, v in d.iteritems() if v > 1]
# prints [1, 3]
```

``````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})
``````

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

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

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

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

for x in list_a:
if x in holding_list:
pass
else:
holding_list.append(x)

print holding_list
``````

# 输出[1,2,3,5,6,7]

``````n = len(list_a)
for i in range(n):
for j in range(i+1, n):
if list_a[i] == list_a[j]:
print list_a[i]
``````

``````seen = set()
for i in list_a:
if i in seen:
print i
else:
``````

``````dups = [x for x in list_a if list_a.count(x) > 1]
``````

### 获取列表中一个或多个（相同）项的所有出现次数和位置

``````>>> alist = ['foo', 'spam', 'egg', 'foo']
>>> foo_indexes = [n for n,x in enumerate(alist) if x=='foo']
>>> foo_indexes
[0, 3]
>>>
``````

### 让我们的函数findindex

``````def indexlist(item2find, list_or_string):
"Returns all indexes of an item in a list or a string"
return [n for n,item in enumerate(list_or_string) if item==item2find]

print(indexlist("1", "010101010"))
``````

``````[1, 3, 5, 7]
``````

## 简单

``````for n, i in enumerate([1, 2, 3, 4, 1]):
if i == 1:
print(n)
``````

``````0
4
``````