简体   繁体   English

如何一次遍历两个列表?

[英]How to iterate through two lists at once?

Suppose I had two lists, foo and bar instantiated as follows: 假设我有两个列表, foobar实例化如下:

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

Suppose, then, I wanted to iterate through the values and print a concatenation like so: 然后,假设我想遍历这些值并打印一个串联,如下所示:

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

Which would give me: 这会给我:

HelloBonjour 你好卓悦

YesOui 是的

NoNon

Would there be method that wouldn't require a count iterator? 是否会有不需要计数迭代器的方法? Perhaps something along the lines of... 也许...

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

is available? 有空吗?

You can use zip : 您可以使用zip

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

Output: 输出:

HelloBonjour
YesOui
NoNon

Zip is something that will help you when both your input lists are of equal size. 当两个输入列表大小相等时,Zip可以为您提供帮助。 If lists are of different size the operation will be performed only on the elements that have pair in the other list. 如果列表大小不同,则仅对另一个列表中成对的元素执行操作。 If you want to fill the missing pairs with something you can use map: 如果您想用一些东西填充缺失的对,可以使用map:

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

output: 输出:

HelloBonjour
YesOui
NoNon

您可以尝试这个人:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM