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?
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().
Create a comparison array by calling == between two arrays. Call . all() method for the result array object to check if the elements are True.
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.
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.
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With