如果你想要一个 numpy 答案,你可以使用np.unique
:
>>> unique,pos = np.unique(A,return_inverse=True) #Finds all unique elements and their positions
>>> counts = np.bincount(pos) #Count the number of each unique element
>>> maxpos = counts.argmax() #Finds the positions of the maximum count
>>> (unique[maxpos],counts[maxpos])
('d', 2)
尽管如果有两个元素具有相同的计数,这将简单地从unique
array.
有了这个,您还可以轻松地按元素计数排序,如下所示:
>>> maxsort = counts.argsort()[::-1]
>>> (unique[maxsort],counts[maxsort])
(array(['d', 'e', 'c', 'b', 'a'],
dtype='|S1'), array([2, 1, 1, 1, 1]))