2014-02-05 111 views
1

假设我有两个列表,foobar实例如下:如何一次迭代两个列表?

foo = ['Hello', 'Yes', 'No'] 
bar = ['Bonjour', 'Oui', 'Non'] 

假设,那么,我想通过数值迭代和打印像这样的连接:

count = 0 
for x in foo: 
    print x + bar[count] 
    count += 1 

这将使我:

HelloBonjour

YesOui

NONON

会不会有,不会要求计数iterator方法?也许沿着...

for x in foo and y in bar: 
    pint x + y 

可用?

回答

13

您可以使用zip

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

输出:

HelloBonjour 
YesOui 
NoNon 
+2

+1拉链。如果你运行的是较旧版本的python(<3),应该注意''itertools.izip()'将会这样做。默认情况下,当前版本的python似乎是懒惰的。 – KChaloux

+0

具体而言,Python 3.x很懒。 Python 2.7仍然是最新的:) – chepner

0

邮编是什么,会帮助你当你的两个输入列表大小相同。如果列表的大小不同,则仅对另一个列表中具有对的元素执行操作。如果你想填的东西缺少对您可以使用地图:

for i,j in map(None,listA,listB): 
    print i+j 

输出:

HelloBonjour 
YesOui 
NoNon 
+1

'itertools.izip_longest''也可以完成这项工作,也许有更清晰的意图。 –

0

你可以试试这个家伙:

print '\n'.join(map(lambda x, y: x+y, foo, bar))