您的位置:首页 > 编程语言 > Python开发

如何在一个for语句中迭代多个可迭代对象

2017-07-29 20:20 411 查看
实际案例

某班学生期末考试成绩,语文、数学和英语分别存储在3个列表中,同时迭代三个列表,计算每个学生的总分。(并行)

某年级有4个班,某次考试每班英语成绩分别存储在4个列表中,依次迭代每个列表,统计全学年成绩高于90分人数。(串行)

案例一:

  我们看完这个案例是不是首先就想起用索引来解决呢?该方法代码如下:

# -*- coding: utf-8 -*-

from random import randint

chinese = [randint(50, 100) for _ in xrange(3)]
math = [randint(50, 100) for _ in xrange(3)]
english = [randint(50, 100) for _ in xrange(3)]

for i in xrange(len(chinese)):
sum = chinese[i] + math[i] + english[i]
print i+1, sum


其输出结果为:

1 234
2 245
3 190


大家有没有想过,这种方式有个局限性,就是chinese 、math 和english 这些可迭代对象必须是支持这种索引操作的。如果它们为生成器就不支持索引操作,进而无法解决该问题。

这里(并行情况),我们推荐使用内置函数zip,它能将多个可迭代对象合并,每次返回一个元组。该方法代码如下:

# -*- coding: utf-8 -*-

from random import randint

chinese = [randint(50, 100) for _ in xrange(3)]
math = [randint(50, 100) for _ in xrange(3)]
english = [randint(50, 100) for _ in xrange(3)]

total = []

for c, m, e in zip(chinese, math, english):
total.append(c+m+e)

for i in xrange(len(chinese)):
print i+1, total[i]


其输出结果为:

1 234
2 245
3 190


案例二(串行):

  解决方案:使用标准库中的itertools.chain,它能将多个可迭代对象连接。该方法代码如下:

# -*- coding: utf-8 -*-

from itertools import chain
from random import randint

e1 = [randint(50, 100) for _ in xrange(3)]
e2 = [randint(50, 100) for _ in xrange(4)]
e3 = [randint(50, 100) for _ in xrange(6)]
e4 = [randint(50, 100) for _ in xrange(10)]

count = 0

for s in chain(e1, e2, e3, e4):
if s > 90:
count += 1

print count


其运行结果为:

8
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息