并行迭代多个序列的2种方法

并行迭代多个序列的2种方法

s 和 t 是两个序列,现在并行迭代这个两个序列

方法一

只用while循环,代码如下:

1
2
3
4
5
6
7
8
9
10
11
s = [1,2,3]
t = ['hockel','joan','tony']
i = 0
z = list()
while i < len(s) and i < len(t):
x = s[i]
y = t[i]
z.append((x,y))
i += 1

print(z)

输出结果如下:

[(1, 'hockel'), (2, 'joan'), (3, 'tony')]

方式二

1
2
3
4
5
6
7
s = [1,2,3]
t = ['hockel','joan','tony']
z = []
for x,y in zip(s,t):
z.append((x,y))

print(z)

输出结果如下:

[(1, 'hockel'), (2, 'joan'), (3, 'tony')]