1. 程式人生 > >python中counter()記數

python中counter()記數

引入 counter sdn start replace pan bsp 含義 itl

一:定義一個list數組,求數組中每個元素出現的次數

如果用Java來實現,是一個比較復雜的,需要遍歷數組list。

但是Python很簡單:看代碼

[python] view plain copy
  1. a = [1,4,2,3,2,3,4,2]
  2. from collections import Counter
  3. print Counter(a)


打印結果:

Counter({2: 3, 3: 2, 4: 2, 1: 1})

結果表示:元素2出現了3次;元素3出現了2次;元素4出現了2次;元素1出現了1次。

二:求數組中出現次數最多的元素

直接看代碼:

[python]
view plain copy
  1. a = [1,4,2,3,2,3,4,2]
  2. from collections import Counter
  3. print Counter(a).most_commo(1)


運行結果:

[(2, 3)]

繼續修改代碼:

[python] view plain copy
  1. a = [1,4,2,3,2,3,4,2]
  2. from collections import Counter
  3. print Counter(a)
  4. print Counter(a).most_common(2)


運行結果:

[(2, 3), (3, 2)]

三:總結

(1)從Collections集合模塊中引入集合類Counter

(2)Counter(a)可以打印出數組a中每個元素出現的次數

(3)Counter(a).most_common(2)可以打印出數組中出現次數最多的元素。參數2表示的含義是:輸出幾個出現次數最多的元素。

轉自:http://blog.csdn.net/u013628152/article/details/43198605

python中counter()記數