python's docs

2.6.0 如何对多个迭代器同时进行操作


0. 目标

某个班级有40个学生,某次考试后,需要统计每个学生语文、英语和数学成绩,并计算总分(并行)

某个年纪有4个班,某次考试后,需要统计整个年级90分以上的学生(串行)


1. 传统方法计算(并行)

>>> from random import randint

>>> chinese = [randint(60, 100) for _ in xrange(40)]

>>> english = [randint(60, 100) for _ in xrange(40)]

>>> math = [randint(60, 100) for _ in xrange(40)]

>>> for stu in xrange(len(math)):
...     print chinese[stu] + english[stu] + math[stu]
...     
286
265
211
260
231
......
260
247
249

2. 使用zip函数(并行)

>>> [x[0]+x[1]+x[2] for x in zip(chinese, english, math)]

[286,
 265,
 211,
 260,
 231,
......
 260,
 247,
 249]

3. 使用itertools.chain串行

>>> from itertools import chain

>>> from random import randint

>>> c1 = [randint(60, 100) for _ in xrange(40)]

>>> c2 = [randint(60, 100) for _ in xrange(40)]

>>> c3 = [randint(60, 100) for _ in xrange(40)]

>>> c4 = [randint(60, 100) for _ in xrange(40)]

>>> for stu in chain(c1, c2, c3, c4):
...     if stu > 90:
...         print stu
...         
100
97
94
93
99
......

98
96
94
96