Python 同时迭代两个列表 [英] Python iterate over two lists simultaneously

查看:31
本文介绍了Python 同时迭代两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 中有没有办法同时 forloop 两个或多个列表?

类似的东西

a = [1,2,3]b = [4,5,6]对于 a,b 中的 x,y:打印 x,y

输出

1 42 53 6

我知道我可以用元组来做到这一点

l = [(1,4), (2,5), (3,6)]对于 x,y 在 l:打印 x,y

解决方案

您可以使用 zip() 函数 配对列表:

对于 zip(a, b) 中的 x, y:

演示:

<预><代码>>>>a = [1,2,3]>>>b = [4,5,6]>>>对于 zip(a, b) 中的 x, y:... 打印 x, y...1 42 53 6

Is there a way in python to forloop over two or more lists simultaneously?

Something like

a = [1,2,3]
b = [4,5,6]
for x,y in a,b:
    print x,y

to output

1 4
2 5
3 6

I know that I can do it with tuples like

l = [(1,4), (2,5), (3,6)]
for x,y in l:
    print x,y

解决方案

You can use the zip() function to pair up lists:

for x, y in zip(a, b):

Demo:

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> for x, y in zip(a, b):
...     print x, y
... 
1 4
2 5
3 6

这篇关于Python 同时迭代两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆