Skip to content
This repository was archived by the owner on May 20, 2022. It is now read-only.

Commit 6eabd8c

Browse files
committed
feat: iterator tools and context
1 parent bef9067 commit 6eabd8c

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

demo-basis/builtin.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,18 @@
44
import base64
55
import hashlib
66
import hmac
7+
import itertools
78
import os
89
from collections import ChainMap
910
from collections import Counter
1011
from collections import OrderedDict
1112
from collections import defaultdict
1213
from collections import deque
1314
from collections import namedtuple
15+
from contextlib import closing
16+
from contextlib import contextmanager
1417
from datetime import datetime
18+
from urllib.request import urlopen
1519

1620
# =======================获取当前日期和时间=======================================
1721

@@ -83,3 +87,48 @@
8387
sha2.update('test sha256'.encode('utf-8'))
8488
print(sha2.hexdigest())
8589
print(hmac.new(b'salt', b'hello dear', digestmod='md5').hexdigest())
90+
91+
# =======================================================迭代工具================================================
92+
93+
# 如果没有重复次数,将无限重复下去
94+
bs = itertools.repeat('a', 8)
95+
for b in bs:
96+
print(b)
97+
# 把一组迭代对象串联起来
98+
bs = itertools.chain('abc', 'def')
99+
for b in bs:
100+
print(b)
101+
# 把迭代器中相邻的重复元素挑出来放在一起
102+
for k, g in itertools.groupby('aaabbbccaa'):
103+
print(k, list(g))
104+
105+
106+
# 更多应用,请参考:
107+
# https://www.liaoxuefeng.com/wiki/1016959663602400/1017783145987360
108+
109+
# ===========================================================上下文管理================================================
110+
111+
class Query(object):
112+
113+
def __init__(self, name: str):
114+
self.name = name
115+
116+
def query(self):
117+
print('query about %s' % self.name)
118+
119+
120+
@contextmanager
121+
def create_query(name: str) -> Query:
122+
print('begin')
123+
q = Query(name)
124+
yield q
125+
print('end')
126+
127+
128+
# 实现了上下文管理的对象,可以使用with语句来实现自动关闭资源
129+
with create_query('bob') as q:
130+
q.query()
131+
# 没有实现上下文管理的,可以用closing来实现
132+
with closing(urlopen('https://www.python.org')) as page:
133+
for line in page:
134+
print(line)

0 commit comments

Comments
 (0)