首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >两个列表元素中的新列表依次弹出。

两个列表元素中的新列表依次弹出。
EN

Code Review用户
提问于 2013-08-06 06:09:56
回答 4查看 3.1K关注 0票数 5

这能被缩短,优化或制造更多的节奏曲吗?

代码语言:javascript
运行
复制
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

EN

回答 4

Code Review用户

发布于 2013-08-06 08:05:23

有几种可能性..。

代码语言:javascript
运行
复制
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):]
票数 1
EN

Code Review用户

发布于 2013-08-06 08:45:22

我会写:

代码语言:javascript
运行
复制
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中添加的(期待已久的) 产自构造的解决方案:

代码语言:javascript
运行
复制
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):])
票数 1
EN

Code Review用户

发布于 2013-08-06 09:57:57

我会避免做x.pop(0),因为太慢了 (顺便说一句,不像x.pop() )。相反,我会写(用Python 2):

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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"])))

以下内容将适用于任何类型的可迭代性:

代码语言:javascript
运行
复制
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
票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/29423

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档