这能被缩短,优化或制造更多的节奏曲吗?
a = [1,9,'foo',5,7]
b = ['bar',4,8,6]
c = []
min_len = min(len(a),len(b))
for i in range(min_len):
c.extend([a.pop(0), b.pop(0)])
c.extend(a)
c.extend(b)
print c
输出:1,“bar”,9,4,‘foo’,8,5,6,7
发布于 2013-08-06 08:05:23
有几种可能性..。
from itertools import chain, izip_longest
def alternate(a, b):
for i in range(max(len(a), len(b))):
if i < len(a):
yield a[i]
if i < len(b):
yield b[i]
def alternate2(list_a, list_b):
unfound = {}
for a, b in izip_longest(list_a, list_b, fill=unfound):
if a is not unfound:
yield a
if b is not unfound:
yield b
a = [1,9,'foo',5,7]
b = ['bar',4,8,6]
print list(alternate(a, b))
print list(alternate2(a, b))
print list(chain.from_iterable(zip(a, b))) + a[len(b):] + b[len(a):]
发布于 2013-08-06 08:45:22
我会写:
import itertools
def alternate(xs, ys):
head = itertools.chain.from_iterable(zip(xs, ys))
return itertools.chain(head, xs[len(ys):], ys[len(xs):])
print(list(alternate([1, 2, 3, 4, 5], ["a", "b", "c"])))
# [1, 'a', 2, 'b', 3, 'c', 4, 5]
另一种不使用itertools
并使用Python 3.3中添加的(期待已久的) 产自构造的解决方案:
def alternate(xs, ys):
yield from (z for zs in zip(xs, ys) for z in zs)
yield from (xs[len(ys):] if len(xs) > len(ys) else ys[len(xs):])
发布于 2013-08-06 09:57:57
我会避免做x.pop(0)
,因为太慢了 (顺便说一句,不像x.pop()
)。相反,我会写(用Python 2):
import itertools
def alternate(a, b):
"""Yield alternatingly from two lists, then yield the remainder of the longer list."""
for A, B in itertools.izip(a, b):
yield A
yield B
for X in a[len(b):] or b[len(a):]:
yield X
print list(alternate([1, 2, 3, 4, 5], ["a", "b", "c"]))
在Python3中,itertools.izip
变成了zip
,正如托克兰所指出的,我们可以在Python3.3中使用yield from
:
def alternate(a, b):
"""Yield alternatingly from two lists, then yield the remainder of the longer list."""
for A, B in zip(a, b):
yield A
yield B
yield from a[len(b):] or b[len(a):]
print(list(alternate([1, 2, 3, 4, 5], ["a", "b", "c"])))
以下内容将适用于任何类型的可迭代性:
def alternate(a, b):
"""Yield alternatingly from two iterables, then yield the remainder of the longer one."""
x, y = iter(a), iter(b)
while True:
try:
yield next(x)
except StopIteration:
yield from y
return
x, y = y, x
https://codereview.stackexchange.com/questions/29423
复制相似问题