让我们创建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']
itertools.chain((...))
可以简单地写作itertools.chain(...)
。哦,而且您可能希望将整个内容封装在list(...)
中。 - arshajiiAnother possibility...
[y for x in izip_longest(l1, l2) for y in x if y is not None]
最简单的方法是使用在itertools
文档中提供的轮询配方:
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']
roundrobin
,该版本在2.x文档中提供。zip_longest()
方法存在的问题,即列表可能包含None
而不被剥离。izip_longest
的解决方案增加了一种简单的修复None
问题的方法。目前我能看到唯一的优点就是速度快,不需要潜在迭代和丢弃大量sentinels。 - jamylakminLen = 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:]
itertools
,它是Python标准库的一部分。 - inspectorG4dgetOut=[]
[(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']
len(zip)
在那里没有定义。 - asmeureritertools.chain()
代替。 - Gareth Latty>>> 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']