python中counter()記數

來源:互聯網
上載者:User

標籤:style   cli   boa   數組   weight   strong   ons   比較   模組   

一:定義一個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()記數

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.