Python Numpy数组元素等价性检查

Python Numpy数组元素等价性检查,python,arrays,numpy,Python,Arrays,Numpy,好的,我对python和numpy还比较陌生,我想做的是取一个随机生成的整数数组,检查每个数字是否多次出现,例如如果b=numpy.array([3,2,33,6,6])它会告诉我6出现两次。或者如果a=numpy.array([22,21888])则每个整数都是不同的 您可以使用检查给定数字在列表或任何可编辑对象中出现的次数: In [2]: from collections import Counter In [8]: b=numpy.array([3,2,33,6,6]) In [9]

好的,我对python和numpy还比较陌生,我想做的是取一个随机生成的整数数组,检查每个数字是否多次出现,例如如果
b=numpy.array([3,2,33,6,6])
它会告诉我6出现两次。或者如果
a=numpy.array([22,21888])
则每个整数都是不同的

您可以使用检查给定数字在列表或任何可编辑对象中出现的次数:

In [2]: from collections import Counter

In [8]: b=numpy.array([3,2,33,6,6])

In [9]: Counter(b)
Out[9]: c = Counter({6: 2, 33: 1, 2: 1, 3: 1})

In [14]: c.most_common(1)
Out[14]: [(6, 2)] # this tells you what is most common element 
                  # if instead of 2 you have 1, you know all elements 
                  # are different.
类似地,您可以为第二个示例执行以下操作:

In [15]: a=numpy.array([22,21,888])

In [16]: Counter(a)
Out[16]: Counter({888: 1, 21: 1, 22: 1})
另一种方法是使用set,并将生成的set长度和数组的长度进行比较

In [20]: len(set(b)) == len(b)
Out[20]: False

In [21]: len(set(a)) == len(a)
Out[21]: True
希望这有帮助