问题描述:

Suppose I had two lists,foo and bar instantiated as follows:

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:

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. 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:

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

output:

HelloBonjour
YesOui
NoNon
网友答案:

You can try this guy:

print '\n'.join( map(lambda x, y: x+y, foo, bar) )
相关阅读:
Top