0

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

4 Answers 4

1

This ought to do it:

''.join([item for sublist in zip(x, y+['']) for item in sublist])
Sign up to request clarification or add additional context in comments.

Comments

0

You want itertools.izip_longest. Also, check out this other post

newStr = ''.join(itertools.chain.from_iterable(
                   itertools.izip_longest(x,y, fillvalue='')
                 ))

1 Comment

More lines! This is too long for a one-liner.
0

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'

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.