1 '''
2 collection
3 Counter用法
4 '''
5 import collections
6 words = ["hello","world","leetcode"]
7 chars = "welldonehoneyr"
8
9 words_cnt = collections.Counter(words)
10 chars_cnt = collections.Counter(chars)
11
12 print(words_cnt)
13 print(chars_cnt)
14
15
16 '''
17 deque:创建双向队列,可以高效实现插入和删除操作,适合用于队列和栈
18 append:往右添加一个元素
19 appenleft:往左添加一个元素
20
21 '''
22 import collections
23 from collections import deque
24
25 words = ["hello","world","leetcode"]
26 words_cnt = collections.Counter(words)
27
28 queue = deque(words)
29 queue.append('dog')
30 queue.appendleft('cat')
31
32 print(queue)
33
34
35 """
36 popleft: 获取最左边的一个元素,并在队列中删除
37 pop:获取最右边的元素,并在队列中删除
38 """
39 words_left = queue.popleft()
40 words_right = queue.pop()
41
42 print(words_left)
43 print(words_right)
44
45 """
46 defaultdict:当使用dict时,若key不存在,可以使用defaultdict返回一个默认值
47 """
48 from collections import defaultdict
49
50 dd = defaultdict(lambda:'None')
51 dd["key1"] = '123'
52
53 print(dd["key1"])
54 print(dd['key2'])