tags:

views:

284

answers:

7

Specifically, I have two lists of strings that I'd like to combine into a string where each line is the next two strings from the lists, separated by spaces:

a = ['foo1', 'foo2', 'foo3']
b = ['bar1', 'bar2', 'bar3']

I want a function combine_to_lines() that would return:

"""foo1 bar1
foo2 bar2
foo3 bar3"""

I admit I've already solved this problem, so I'm going to post the answer. But perhaps someone else has a better one or sees a flaw in mine.

Update: I over-simplified my example above. In my real-world problem the lines were formatted in a more complicated manner that required the tuples returned from zip() to be unpacked. But kudos to mhawke for coming up to the simplest solution to this example.

A: 

Are you asking about the zip function?

S.Lott
Yes. I couldn't remember it, and a Google search took a little time to jog my memory. Perhaps this question will come up in future searches.
Daryl Spitzer
+2  A: 

The zip function "returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables."

def combine_to_lines(list1, list2):
    return '\n'.join([' '.join((a, b)) for a, b in zip(list1, list2)])
Daryl Spitzer
+3  A: 
>>> a = ['foo1', 'foo2', 'foo3']
>>> b = ['bar1', 'bar2', 'bar3']
>>> for i in zip(a,b):
...   print ' '.join(i)
...
foo1 bar1
foo2 bar2
foo3 bar3
ghostdog74
A: 

Here's a one-liner. Could do x + ' ' + y if you were so inclined, not sure if it would be slower or not.

>>> a = ['foo1', 'foo2' , 'foo3']
>>> b = ['bar1', 'bar2', 'bar3']
>>> '\n'.join(' '.join([x,y]) for (x,y) in zip(a,b))
'foo1 bar1\nfoo2 bar2\nfoo3 bar3'
>>> print _
foo1 bar1
foo2 bar2
foo3 bar3
Mark Rushakoff
A: 
'\n'.join(((str(x) + ' ' + str(y)) for (x, y) in zip(a, b)))
Pavel Minaev
A: 

Simple as:

" ".join([a[x] + " " + b[x] for x in range(len(a))])
Denis M
where are the new lines?
mhawke
+6  A: 

It's not necessary to unpack and repack the tuples returned by zip:

'\n'.join(' '.join(x) for x in zip(a, b))
mhawke