How to compare values ​​inside an array in Python - find out if 2 values ​​are the same

Basically I have an array of 50 integers, and I need to find out if any of the 50 integers is equal, and if so, I need to perform an action.

How should I do it? As far as I know, there is currently no function in Python that does this?

+5
source share
5 answers

If you mean that you have a list and you want to know if there are any duplicate values, then make a set from the list and see if it is shorter than the list:

if len(set(my_list)) < len(my_list):
    print "There a dupe!"

This will not tell you what a double value is.

+9
source

Python 2.7+, Counter.

>>> import collections
>>> input = [1, 1, 3, 6, 4, 8, 8, 5, 6]
>>> c = collections.Counter(input)
>>> c
Counter({1: 2, 6: 2, 8: 2, 3: 1, 4: 1, 5: 1})
>>> duplicates = [i for i in c if c[i] > 1]
>>> duplicates
[1, 6, 8]
+5

, groupby .

>>> from itertools import groupby
>>> for x in groupby([1,1,2,2,2,3]):
...     print x[0],len(list(x[1]))
... 
1 2
2 3
3 1

- , - . groupby , , , .

>>> for x in groupby(sorted([1,1,2,4,2,2,3])):
...     print x[0],len(list(x[1]))
... 
1 2
2 3
3 1
4 1
+2

Set .

>>> a = [1, 2, 3]
>>> len(set(a)) == len(a)
True
>>> a = [1, 2, 3, 4, 4]
>>> len(set(a)) == len(a)
False
+1
>>> arbitrary_list = [1, 1, 2, 3, 4, 4, 4]
>>> item_occurence = dict([(item, list.count(item)) for item in arbitrary_list])
{1: 2, 2: 1, 3: 1, 4: 3}

, ,

>>> filter(lambda item: item_occurence[item] > 1, item_occurence)
[1, 4]
0

All Articles