Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare values within an array in Python - find out whether 2 values are the same

I basically have an array of 50 integers, and I need to find out whether any of the 50 integers are equal, and if they are, I need to carry out an action.

How would I go about doing this? As far as I know there isn't currently a function in Python that does this is there?

like image 348
Taimur Avatar asked Jul 21 '11 17:07

Taimur


People also ask

How do you check if there are same values in an array Python?

Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count().

How do you compare two elements in an array in Python?

Create a comparison array by calling == between two arrays. Call . all() method for the result array object to check if the elements are True.

How do you compare 2 numbers in an array?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.


3 Answers

If you mean 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's shorter than the list:

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

This won't tell you what the duplicate value is, though.

like image 125
Ned Batchelder Avatar answered Oct 19 '22 10:10

Ned Batchelder


If you have Python 2.7+ you can use 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]
like image 28
Paolo Moretti Avatar answered Oct 19 '22 10:10

Paolo Moretti


If your actions need to know the number or how many times that number gets repeated over your input list then groupby is a good choice.

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

The first number is the element and the second the number of repetitions. groupby works over a sorted list so make sure you sort your input list, for instance.

>>> 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
like image 31
Manuel Salvadores Avatar answered Oct 19 '22 11:10

Manuel Salvadores