|
| 1 | +''' |
| 2 | +File: element_count.py |
| 3 | +Project: 01-DataSturcture |
| 4 | +=========== |
| 5 | +File Created: Monday, 20th July 2020 10:41:10 pm |
| 6 | +Author: <<LanLing>> (<<[email protected]>>) |
| 7 | +=========== |
| 8 | +Last Modified: Monday, 20th July 2020 10:41:15 pm |
| 9 | +Modified By: <<LanLing>> (<<[email protected]>>>) |
| 10 | +=========== |
| 11 | +Description: 序列中出现次数最多的元素 |
| 12 | +Copyright <<2020>> - 2020 Your Company, <<XDU>> |
| 13 | +''' |
| 14 | +from collections import Counter |
| 15 | + |
| 16 | + |
| 17 | +# 出现频率最高的3个单词 |
| 18 | +words = [ |
| 19 | + 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', |
| 20 | + 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', |
| 21 | + 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', |
| 22 | + 'my', 'eyes', "you're", 'under' |
| 23 | +] |
| 24 | +word_counts = Counter(words) |
| 25 | +# 出现频率最高的3个单词 |
| 26 | +top_three = word_counts.most_common(3) |
| 27 | +print(top_three) |
| 28 | +# 字典,将元素映射到出现次数中 |
| 29 | +print(word_counts['look']) |
| 30 | + |
| 31 | + |
| 32 | +# 更新词汇表 |
| 33 | +morewords = ['why', 'are', 'you', 'not', 'looking', 'in', 'my', 'eyes'] |
| 34 | +word_counts.update(morewords) |
| 35 | +print(word_counts['eyes']) |
| 36 | + |
| 37 | + |
| 38 | +# Counter 对象在几乎所有需要制表或者计数数据的场合是非常有用的工具。 |
| 39 | +# 在解决这类问题的时候你应该优先选择它,而不是手动的利用字典去实现。 |
| 40 | +a = Counter(words) |
| 41 | +b = Counter(morewords) |
| 42 | + |
| 43 | +# 直接操作 |
| 44 | +c = a + b |
| 45 | +d = a - b |
| 46 | +print(c, '\n', d) |
0 commit comments