Reputation: 30687
so i have two different lists of strings; i.e. x and y.
len(y) = len(x) - 1
i want to add them together in an empty string in the original order so basically the output = x1 + y1 + x2 + y2 + x3
x = ['AAA','BBB','CCC']
y = ['abab','bcbcb']
#z = ''
z = 'AAAababBBBbcbcbCCC'
how can i create a for-loop to add to this empty string z ?
i usually would do:
for p,q in zip(x,y):
but since y in smaller than x, it wouldn't add the last value of x
Upvotes: 0
Views: 187
Reputation: 2037
from itertools import izip_longest
x = ['AAA','BBB','CCC']
y = ['abab','bcbcb']
unfinished_z = izip_longest( x,y,fillvalue='' ) # an iterator
unfinished_z = [ ''.join( text ) for text in unfinished_z ] # a list
z = ''.join( unfinished_z ) # the string AAAababBBBbcbcbCCC
I prefer more verbosity.
Upvotes: 0
Reputation: 250951
You can use the roundrobin
recipe from itertools:
from itertools import *
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
x = ['AAA','BBB','CCC']
y = ['abab','bcbcb']
print "".join(roundrobin(x,y))
#AAAababBBBbcbcbCCC
Or with itertools.izip_longest
you could do:
>>> from itertools import izip_longest
>>> ''.join([''.join(c) for c in izip_longest(x,y,fillvalue = '')])
'AAAababBBBbcbcbCCC'
Upvotes: 0
Reputation: 6010
This ought to do it:
''.join([item for sublist in zip(x, y+['']) for item in sublist])
Upvotes: 1
Reputation: 113955
You want itertools.izip_longest
. Also, check out this other post
newStr = ''.join(itertools.chain.from_iterable(
itertools.izip_longest(x,y, fillvalue='')
))
Upvotes: 0