forked from yidao620c/python3-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollections.py
More file actions
36 lines (29 loc) · 993 Bytes
/
collections.py
File metadata and controls
36 lines (29 loc) · 993 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic:
collections中几个有用的数据结构
deque: 高效的双端队列
defaultdict: 类似dict,对于缺少key处理更优雅
namedtuple: 命名tuple
"""
from collections import deque
from collections import defaultdict
from collections import namedtuple
__author__ = 'Xiong Neng'
def main():
s = "yeah but no but yeah but no test good"
words = s.split()
# key不存在时调用list()函数,并保存为key对应的value
word_locs = defaultdict(list)
for n, w in enumerate(words):
word_locs[w].append(n)
print(word_locs)
# 如果定义仅用作数据结构的对象,最好使用命名tuple,无需定义一个类
network_address = namedtuple('network', ['hostname', 'port'])
a = network_address('www.python.org', 80)
print(a.hostname, a.port, sep='-')
print(type(a)) # <class '__main__.network'>
pass
if __name__ == '__main__':
main()