-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathyield_from_tutorial.py
More file actions
60 lines (42 loc) · 987 Bytes
/
yield_from_tutorial.py
File metadata and controls
60 lines (42 loc) · 987 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Using yield from allows us to avoid having to deal with unexpected exceptions,
# let us focus on the implementation of business code.
def demo(n):
i = 0
while i < n:
yield i
i += 1
def test_yield_from(n):
print("test_yield_from start")
yield from demo(n)
# 相當於下面
# for item in demo(n):
# yield item
print("test_yield_from end")
def example_1():
for i in test_yield_from(3):
print(i)
def return_yield():
yield from (
i
for i in range(5)
)
def example_2():
result = return_yield()
print(next(result))
print(next(result))
def chain_old(*iterables):
for it in iterables:
for i in it:
yield i
def chain(*iterables):
for it in iterables:
yield from it
def example_3():
s = 'ABC'
t = tuple(range(3))
show = list(chain(s, t))
print(show)
if __name__ == "__main__":
example_1()
example_2()
example_3()