2013-07-12 65 views
0

所以我有兩個不同的字符串列表;即x和y。向不同列表中的字符串添加兩個不同的值

len(y) = len(x) - 1 

我想他們在原來的順序一個空字符串加在一起所以基本上輸出= X1 + Y1 + X2 + Y2 + X3

x = ['AAA','BBB','CCC'] 
y = ['abab','bcbcb'] 

#z = '' 
z = 'AAAababBBBbcbcbCCC' 

如何創建一個for循環添加到這個空字符串z?

我通常會做:

for p,q in zip(x,y): 

但由於在小於X Y,它不會添加X

回答

0

您可以使用從itertools的roundrobinrecipe

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   

或者與itertools.izip_longest你可以這樣做:

>>> from itertools import izip_longest 
>>> ''.join([''.join(c) for c in izip_longest(x,y,fillvalue = '')]) 
'AAAababBBBbcbcbCCC' 
1

這應該做到這一點:

''.join([item for sublist in zip(x, y+['']) for item in sublist]) 
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 

我更喜歡更多的冗長。

相關問題