如何在一个for语句中迭代多个可迭代对象
2017-07-29 20:20
411 查看
实际案例
某班学生期末考试成绩,语文、数学和英语分别存储在3个列表中,同时迭代三个列表,计算每个学生的总分。(并行)
某年级有4个班,某次考试每班英语成绩分别存储在4个列表中,依次迭代每个列表,统计全学年成绩高于90分人数。(串行)
案例一:
我们看完这个案例是不是首先就想起用索引来解决呢?该方法代码如下:
其输出结果为:
大家有没有想过,这种方式有个局限性,就是chinese 、math 和english 这些可迭代对象必须是支持这种索引操作的。如果它们为生成器就不支持索引操作,进而无法解决该问题。
这里(并行情况),我们推荐使用内置函数zip,它能将多个可迭代对象合并,每次返回一个元组。该方法代码如下:
其输出结果为:
案例二(串行):
解决方案:使用标准库中的itertools.chain,它能将多个可迭代对象连接。该方法代码如下:
其运行结果为:
某班学生期末考试成绩,语文、数学和英语分别存储在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
相关文章推荐
- python 3-6 如何在一个for语句中迭代多个可迭代对象zip/itertools.chain
- python-10-如何在一个for语句中迭代多个可迭代对象?
- 【慕课网】如何在一个for语句中迭代多个可迭代对象?
- python_如何在一个for循环中迭代多个可迭代对象?
- 【笔记】如何在for语句中迭代多个可迭代对象
- Python高级编程-如何在在一个for循环中迭代多个可迭代对象
- 3-6在一个for语句中迭代多个可迭代对象
- 探寻Python中如何同时迭代多个iterable对象
- 原创---switch(T obj)选择语句如何判断是某一个对象
- 如果一个Object对象可能是数组那么如何对其进行迭代
- Oracle 如何查询一个对象的完整定义语句 .
- 如果一个Object对象可能是集合或者数组那么如何对其进行迭代
- python中如何将两个list合并成一个list,不用for语句
- 在python中如何将两个list合并成一个list,不用for语句
- 如何判断一个表是否建立索引约束等信息的SQL语句
- Javascript面试题:如何给一个Javascript的对象属性赋值?如何取得属性值?
- switch语句中的case后面的分枝值如何指定一个范围
- Oracle数据库查看一个进程是如何执行相关的实际SQL语句
- 在C#如何遍历一个对象的所有属性
- OC-003.如何去创建一个NSString的对象