让我们有 2 个列表
l1 = [1, 2, 3]
l2 = [a, b, c, d, e, f, g...]
结果:
list = [1, a, 2, b, 3, c, d, e, f, g...]
不能使用zip()
,因为它会将结果缩短到最小list
。我还需要list
输出而不是iterable
.
>>> l1 = [1,2,3]
>>> l2 = ['a','b','c','d','e','f','g']
>>> [i for i in itertools.chain(*itertools.izip_longest(l1,l2)) if i is not None]
[1, 'a', 2, 'b', 3, 'c', 'd', 'e', 'f', 'g']
要允许None
值包含在列表中,您可以使用以下修改:
>>> from itertools import chain, izip_longest
>>> l1 = [1, None, 2, 3]
>>> l2 = ['a','b','c','d','e','f','g']
>>> sentinel = object()
>>> [i
for i in chain(*izip_longest(l1, l2, fillvalue=sentinel))
if i is not sentinel]
[1, 'a', None, 'b', 2, 'c', 3, 'd', 'e', 'f', 'g']
另一种可能...
[y for x in izip_longest(l1, l2) for y in x if y is not None]
(当然,在从 itertools 导入 izip_longest 之后)
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))
可以这样使用:
>>> l1 = [1,2,3]
>>> l2 = ["a", "b", "c", "d", "e", "f", "g"]
>>> list(roundrobin(l1, l2))
[1, 'a', 2, 'b', 3, 'c', 'd', 'e', 'f', 'g']
请注意,2.x 需要稍有不同的 2.x 文档roundrobin
中提供的版本。
这也避免了该zip_longest()
方法存在的问题,即列表可以包含None
而不被剥离。
minLen = len(l1) if len(l1) < len(l2) else len(l2)
for i in range(0, minLen):
list[2*i] = l1[i]
list[2*i+1] = l2[i]
list[i*2+2:] = l1[i+1:] if len(l1) > len(l2) else l2[i+1:]
这不是一条捷径,但它消除了不必要的依赖。
更新:这是@jsvk 建议的另一种方式
mixed = []
for i in range( len(min(l1, l2)) ):
mixed.append(l1[i])
mixed.append(l2[i])
list += max(l1, l2)[i+1:]
如果您需要单个列表中的输出,而不是元组列表,请试试这个。
Out=[]
[(Out.extend(i) for i in (itertools.izip_longest(l1,l2))]
Out=filter(None, Out)
我并没有声称这是最好的方法,但我只是想指出可以使用 zip:
b = zip(l1, l2)
a = []
[a.extend(i) for i in b]
a.extend(max([l1, l2], key=len)[len(b):])
>>> a
[1, 'a', 2, 'b', 3, 'c', 'd', 'e', 'f', 'g']
>>> a = [1, 2, 3]
>>> b = list("abcdefg")
>>> [x for e in zip(a, b) for x in e] + b[len(a):]
[1, 'a', 2, 'b', 3, 'c', 'd', 'e', 'f', 'g']