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

Jackey Python 879 次浏览 , 没有评论
# 如何在一个for语句中迭代多个可迭代对象

# 并行
from random import randint

from mrjob.py2 import xrange

chinese = [randint(60, 100) for _ in xrange(40)]
math = [randint(60, 100) for _ in xrange(40)]
english = [randint(60, 100) for _ in xrange(40)]
print(chinese)

for i in xrange(len(math)):
    print(chinese[i] + english[i] + math[i])

res = zip([1, 2, 3, 4], ('a', 'b', 'c', 'd'))
print(list(res))

# 长度不一致时,按最短的取
res = zip([1, 2, 3, 4], ('a', 'b', 'c'))
print(list(res))

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

print(total)

# 串行
from itertools import chain

for x in chain([1, 2, 3, 4], ('a', 'b', 'c')):
    print(x)

e1 = [randint(60, 100) for _ in xrange(40)]
e2 = [randint(60, 100) for _ in xrange(42)]
e3 = [randint(60, 100) for _ in xrange(42)]
e4 = [randint(60, 100) for _ in xrange(39)]

# 统计90分以上的人数
count = 0
for s in chain(e1, e2, e3, e4):
    if s > 90:
        count += 1

print(count)

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Go