Python同时迭代两个列表

标签 python list python-2.7 foreach iteration

有没有办法在 python 中同时循环两个或多个列表?

类似

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

输出

1 4
2 5
3 6

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

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]
>>> for x, y in zip(a, b):
...     print x, y
... 
1 4
2 5
3 6

关于Python同时迭代两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21098350/

相关文章:

c - 用C语言实现栈和链表

python-2.7 - 我可以通过 Keras 将图像添加到 Tensorboard 吗?

python - 如何使用 Python 在 Ubuntu 上创建文件快捷方式?

python - 如何使该算法在执行除法运算时返回整数?

r - R 中的 "Only the first element of list is used"

python - 正则表达式: match within a match

python - (如何)我可以在 jupyter (ipython) 中并排运行 python 2.7 和 3.4 笔记本吗?

python - reshape (60000, 28, 28, 1) 是什么意思?

python - Python YQL 入门

python - 从词典列表到词典