您可以使用 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'