Python同时迭代两个列表 [英] Python iterate over two lists simultaneously
本文介绍了Python同时迭代两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
类似于
<$ p
有没有一种方法可以在python中同时查找两个或多个列表? x,y在a中,b:
print x,
$ y
输出
1 4
2 5
3 6
I知道我可以用元组来做到这一点,比如
$ p code> l = [(1,4),(2,5),(3) ,6)]
for x,y in l:
print x,y
zip( )
function 配对列表: for x,y in zip(a ,b):
演示:
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> x,y in zip(a,b):
... print x,y
...
1 4
2 5
3 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屋!
查看全文