Counting elements in a list


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
  2. [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
  3. Type "help", "copyright", "credits" or "license" for more information.
  4. >>> word_list = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', '']
  5. >>> word_counter = {}
  6. >>> for word in word_list:
  7. ... if word in word_counter:
  8. ... word_counter[word] += 1
  9. ... else:
  10. ... word_counter[word] = 1
  11. ...
  12. >>> popular_words = sorted(word_counter, key = word_counter.get, reverse = True)
  13. >>>
  14. >>> top_3 = popular_words[:3]
  15. >>>
  16. >>> top_3
  17. ['Jellicle', 'Cats', 'and']
  18.  
  19.  
  20.  
  21.  
  22. ## OR .....
  23.  
  24.  
  25.  
  26. >>> l = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', '']
  27. >>> counter = {}
  28. >>> for i in l: counter[i] = counter.get(i, 0) + 1
  29. ...
  30. >>> counter
  31. {'and': 3, '': 1, 'merry': 1, 'rise.': 1, 'small;': 1, 'Moon': 1, 'cheerful': 1, 'bright': 1, 'Cats': 5, 'are': 3, 'have': 2, 'bright,': 1, 'for': 1, 'their': 1, 'rather': 1, 'when': 1, 'to': 3, 'airs': 1, 'black': 2, 'They': 1, 'practise': 1, 'caterwaul.': 1, 'pleasant': 1, 'hear': 1, 'they': 1, 'white,': 1, 'wait': 1, 'And': 2, 'like': 1, 'Jellicle': 6, 'eyes;': 1, 'the': 1, 'faces,': 1, 'graces': 1}
  32. >>> sorted([ (freq,word) for word, freq in counter.items() ], reverse=True)[:3]
  33. [(6, 'Jellicle'), (5, 'Cats'), (3, 'to')]

URL: http://stackoverflow.com/questions/3594514/how-to-find-most-common-elements-of-a-list

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.