================================ 1.12 åºåˆ—ä¸å‡ºçŽ°æ¬¡æ•°æœ€å¤šçš„å…ƒç´ ================================ ---------- 问题 ---------- æ€Žæ ·æ‰¾å‡ºä¸€ä¸ªåºåˆ—ä¸å‡ºçŽ°æ¬¡æ•°æœ€å¤šçš„å…ƒç´ å‘¢ï¼Ÿ ---------- 解决方案 ---------- ``collections.Counter`` 类就是专门为这类问题而设计的, 它甚至有一个有用的 ``most_common()`` æ–¹æ³•ç›´æŽ¥ç»™äº†ä½ ç”æ¡ˆã€‚ 为了演示,先å‡è®¾ä½ 有一个å•è¯åˆ—表并且想找出哪个å•è¯å‡ºçŽ°é¢‘çŽ‡æœ€é«˜ã€‚ä½ å¯ä»¥è¿™æ ·åšï¼š .. code-block:: python words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ] from collections import Counter word_counts = Counter(words) # 出现频率最高的3个å•è¯ top_three = word_counts.most_common(3) print(top_three) # Outputs [('eyes', 8), ('the', 5), ('look', 4)] ---------- 讨论 ---------- 作为输入, ``Counter`` 对象å¯ä»¥æŽ¥å—ä»»æ„的由å¯å“ˆå¸Œï¼ˆ``hashable``ï¼‰å…ƒç´ æž„æˆçš„åºåˆ—对象。 在底层实现上,一个 ``Counter`` 对象就是一个å—å…¸ï¼Œå°†å…ƒç´ æ˜ å°„åˆ°å®ƒå‡ºçŽ°çš„æ¬¡æ•°ä¸Šã€‚æ¯”å¦‚ï¼š .. code-block:: python >>> word_counts['not'] 1 >>> word_counts['eyes'] 8 >>> å¦‚æžœä½ æƒ³æ‰‹åŠ¨å¢žåŠ è®¡æ•°ï¼Œå¯ä»¥ç®€å•çš„ç”¨åŠ æ³•ï¼š .. code-block:: python >>> morewords = ['why','are','you','not','looking','in','my','eyes'] >>> for word in morewords: ... word_counts[word] += 1 ... >>> word_counts['eyes'] 9 >>> æˆ–è€…ä½ å¯ä»¥ä½¿ç”¨ ``update()`` 方法: .. code-block:: python >>> word_counts.update(morewords) >>> ``Counter`` 实例一个鲜为人知的特性是它们å¯ä»¥å¾ˆå®¹æ˜“的跟数å¦è¿ç®—æ“作相结åˆã€‚比如: .. code-block:: python >>> a = Counter(words) >>> b = Counter(morewords) >>> a Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2, "you're": 1, "don't": 1, 'under': 1, 'not': 1}) >>> b Counter({'eyes': 1, 'looking': 1, 'are': 1, 'in': 1, 'not': 1, 'you': 1, 'my': 1, 'why': 1}) >>> # Combine counts >>> c = a + b >>> c Counter({'eyes': 9, 'the': 5, 'look': 4, 'my': 4, 'into': 3, 'not': 2, 'around': 2, "you're": 1, "don't": 1, 'in': 1, 'why': 1, 'looking': 1, 'are': 1, 'under': 1, 'you': 1}) >>> # Subtract counts >>> d = a - b >>> d Counter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'my': 2, 'around': 2, "you're": 1, "don't": 1, 'under': 1}) >>> æ¯«æ— ç–‘é—®ï¼Œ ``Counter`` å¯¹è±¡åœ¨å‡ ä¹Žæ‰€æœ‰éœ€è¦åˆ¶è¡¨æˆ–者计数数æ®çš„åœºåˆæ˜¯éžå¸¸æœ‰ç”¨çš„工具。 åœ¨è§£å†³è¿™ç±»é—®é¢˜çš„æ—¶å€™ä½ åº”è¯¥ä¼˜å…ˆé€‰æ‹©å®ƒï¼Œè€Œä¸æ˜¯æ‰‹åŠ¨çš„åˆ©ç”¨å—典去实现。