如何一次遍历两个列表?

Nan*_*nor 1 python list

假设我有两个列表,foobar实例化如下:

foo = ['Hello', 'Yes', 'No']
bar = ['Bonjour', 'Oui', 'Non']
Run Code Online (Sandbox Code Playgroud)

那么,假设我想遍历这些值并打印如下的连接:

count = 0
for x in foo:
    print x + bar[count]
    count += 1
Run Code Online (Sandbox Code Playgroud)

哪个会给我:

HelloBonjour

YesOui

NONON

是否有方法不需要计数迭代器?也许是......

for x in foo and y in bar:
    pint x + y
Run Code Online (Sandbox Code Playgroud)

可以吗?

YS-*_*S-L 13

你可以使用zip:

foo = ['Hello', 'Yes', 'No']
bar = ['Bonjour', 'Oui', 'Non']
for x, y in zip(foo, bar):
    print x + y
Run Code Online (Sandbox Code Playgroud)

输出:

HelloBonjour
YesOui
NoNon
Run Code Online (Sandbox Code Playgroud)

  • 拉链+1.如果你运行的是旧版本的python(<3),应该注意`itertools.izip()`会懒得做.当前版本的python默认似乎是懒惰的. (2认同)