标签:lis 个学生 并行 span 存储 class [] python python3
案例:
如何解决?
1. 方法1:通过索引
#!/usr/bin/python3 from random import randint def get_result(chinese, math, english): total = [] # 循环索引进行取值,毕竟列表等长且成绩对应 for index in range(len(chinese)): total.append(chinese[index] + math[index] + english[index]) return total if __name__ == ‘__main__‘: # 生成 3 个成绩列表 chinese = [randint(60, 100) for _ in range(40)] math = [randint(60, 100) for _ in range(40)] english = [randint(60, 100) for _ in range(40)] # 统计 总成绩 total = get_result(chinese, math, english) for x in total: print(x)
方法2: 通过zip函数,同时迭代3个列表
#!/usr/bin/python3 from random import randint def get_result(chinese, math, english): total = [] # 通过zip函数进行迭代,实现同时迭代 3 个对象 for c, m, e in zip(chinese, math, english): print(c, m, e) total.append(c + m + e) return total if __name__ == ‘__main__‘: # 生成 3 个成绩列表 chinese = [randint(60, 100) for _ in range(40)] math = [randint(60, 100) for _ in range(40)] english = [randint(60, 100) for _ in range(40)] # 统计 总成绩 total = get_result(chinese, math, english) for x in total: print(x)
2. 方法1: 通过 itertools中 chain方法
#!/usr/bin/python3 from random import randint from itertools import chain def get_result(e1, e2, e3): # 通过chain函数进行连续窜行迭代3个列表 for i in chain(e1, e2, e3): print(i) if __name__ == ‘__main__‘: # 生成 3 个班成绩单,1班36人,2班43人,3班40人 e1 = [randint(60, 100) for _ in range(36)] e2 = [randint(60, 100) for _ in range(43)] e3 = [randint(60, 100) for _ in range(40)] # 依次打印成绩 get_result(e1, e2, e3)
标签:lis 个学生 并行 span 存储 class [] python python3
原文地址:http://www.cnblogs.com/2bjiujiu/p/7253169.html