您可以使用從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'
更多線條!對於單線來說這太長了。 – user2357112
這讀起來更好。 – user2357112