所以我有两个不同的字符串列表;即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
的最后一个值答案 0 :(得分:1)
应该这样做:
''.join([item for sublist in zip(x, y+['']) for item in sublist])
答案 1 :(得分:0)
你想要itertools.izip_longest
。另外,请查看this other post
newStr = ''.join(itertools.chain.from_iterable(
itertools.izip_longest(x,y, fillvalue='')
))
答案 2 :(得分:0)
您可以使用itertools中的roundrobin
recipe:
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'
答案 3 :(得分: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
我更喜欢冗长。