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

但由于 y 小于 x,它不会添加 x 的最后一个值

4

4 回答 4

1

这应该这样做:

''.join([item for sublist in zip(x, y+['']) for item in sublist])
于 2013-07-12T21:21:05.977 回答
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

我更喜欢冗长。

于 2013-07-15T16:08:03.807 回答
0

你想要itertools.izip_longest。另外,看看这个其他帖子

newStr = ''.join(itertools.chain.from_iterable(
                   itertools.izip_longest(x,y, fillvalue='')
                 ))
于 2013-07-12T21:14:33.547 回答
0

您可以使用 itertools 中的roundrobin 配方

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'
于 2013-07-12T21:16:15.040 回答