File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python
2+ # -*- encoding: utf-8 -*-
3+ """
4+ Topic: 在不同容器中迭代
5+ Desc :
6+ """
7+ from itertools import chain
8+
9+
10+ def iter_separate ():
11+ a = [1 , 2 , 3 , 4 ]
12+ b = ['x' , 'y' , 'z' ]
13+ for x in chain (a , b ):
14+ print (x )
15+
16+ if __name__ == '__main__' :
17+ iter_separate ()
18+
Original file line number Diff line number Diff line change 55----------
66问题
77----------
8- todo...
8+ 你想在多个对象执行相同的操作,但是这些对象在不同的容器中,你希望代码在不失可读性的情况下避免写重复的循环。
9+
10+ |
911
1012----------
1113解决方案
1214----------
13- todo...
15+ itertools.chain()方法可以用来简化这个任务。
16+ 它接受一个可迭代对象列表作为输入,并返回一个迭代器,有效的屏蔽掉在多个容器中迭代细节。
17+ 为了演示清楚,考虑下面这个例子:
18+
19+ .. code-block :: python
20+
21+ >> > from itertools import chain
22+ >> > a = [1 , 2 , 3 , 4 ]
23+ >> > b = [' x' , ' y' , ' z' ]
24+ >> > for x in chain(a, b):
25+ ... print (x)
26+ ...
27+ 1
28+ 2
29+ 3
30+ 4
31+ x
32+ y
33+ z
34+ >> >
35+
36+ 使用chain()的一个常见场景是当你想对不同的集合中所有元素执行某些操作的时候。比如:
37+
38+ .. code-block :: python
39+
40+ # Various working sets of items
41+ active_items = set ()
42+ inactive_items = set ()
43+
44+ # Iterate over all items
45+ for item in chain(active_items, inactive_items):
46+ # Process item
47+
48+ 这种解决方案要比像下面这样使用两个单独的循环更加优雅,
49+
50+ .. code-block :: python
51+
52+ for item in active_items:
53+ # Process item
54+ ...
55+
56+ for item in inactive_items:
57+ # Process item
58+ ...
1459
1560----------
1661讨论
1762----------
18- todo...
63+ itertools.chain()接受一个或多个可迭代对象最为输入参数。
64+ 然后创建一个迭代器,依次连续的返回每个可迭代对象中的元素。
65+ 这种方式要比先将序列合并再迭代要高效的多。比如:
66+
67+ .. code-block :: python
68+
69+ # Inefficent
70+ for x in a + b:
71+ ...
72+
73+ # Better
74+ for x in chain(a, b):
75+ ...
76+
77+ 第一种方案中,a + b操作会创建一个全新的序列并要求a和b的类型一致。
78+ chian()不会有这一步,所以如果输入序列非常大的时候会很省内存。
79+ 并且当可迭代对象类型不一样的时候chain()同样可以很好的工作。
80+
You can’t perform that action at this time.
0 commit comments