numpy:
>>>x = np.array([2,3,1,1,4])
>>>count = np.bincount(x)
array([0, 2, 1, 1, 1])
>>>common_value = np.argmax(count)
1
dict:
>>>a={'a':4,'b':2,'c':3,'d':1}
>>>max(a)
'd' #按键排序
>>>max(a,key=a.get)
'a' #按值排序
>>>sorted(a)
['a','b','c','d'] #按键排序
>>>sorted(a,reverse=True)
['d','c','b','a'] #按键排序
>>>sorted(a,key=a.get)
['d','b','c','a'] #按值排序
>>>sorted(a.items())
[('a',4),('b',2),('c',3),('d',1)] #按键排序
>>>max(a.items())
('d',1) #按键排序
for遍历:
>>>arr=np.array([[7,7,2,1],[12,7,6,4],[6,6,7,9],[0,2,3,3]])
>>>tu=sorted([(np.sum(arr==i),i) for i in set(arr.flat)])
>>>print('个数最多元素为 {1} 有 {0} 个'.format(*tu[-1]))
个数最多元素为 7 有 4 个
对于:tu=sorted([(np.sum(arr==i),i) for i in set(arr.flat)])解析
*与**解析可参考:http://blog.csdn.net/l297969586/article/details/77879117
列表元素的遍历寻找(np.array也适用)
>>>a=[1,2,2,3,3,3]
>>>dict(collections.Counter(lst))
{1:1,2:2,3:3}
>>>dict(zip(*np.unique(lst, return_counts=True)))
{1:1,2:2,3:3}
unique:
>>>a=np.array([[1,2,3,4],[2,5,6,7])
>>>np.unique(a,return_index=True,return_counts=True)
(array([1,2,3,4,5,6,7]),array([0,1,2,3,5,6,7]),array([1,2,1,1,1,1,1]),dtype=int64)