python - 交错 2 个长度不等的列表

标签 python list for-loop indexing

<分区>

我希望能够交错两个长度可能不相等的列表。我有的是:

  def interleave(xs,ys):
    a=xs
    b=ys
    c=a+b
    c[::2]=a
    c[1::2]=b
    return c

这适用于长度相等或只有 +/-1 的列表。但是如果我们说 xs=[1,2,3] 和 ys= ["hi,"bye","no","yes","why"] 这条消息出现:

c[::2]=a
ValueError: attempt to assign sequence of size 3 to extended slice of size 4

如何使用索引解决此问题?还是我必须使用 for 循环? 编辑:我想要的是让额外的值出现在最后。

最佳答案

您可以使用 itertools.izip_longest这里:

>>> from itertools import izip_longest
>>> xs = [1,2,3]
>>> ys = ["hi","bye","no","yes","why"]
>>> s = object()
>>> [y for x in izip_longest(xs, ys, fillvalue=s) for y in x if y is not s]
[1, 'hi', 2, 'bye', 3, 'no', 'yes', 'why']

使用来自 itertoolsroundrobin 配方,这里不需要哨兵值:

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))

演示:

>>> list(roundrobin(xs, ys))
[1, 'hi', 2, 'bye', 3, 'no', 'yes', 'why']
>>> list(roundrobin(ys, xs))
['hi', 1, 'bye', 2, 'no', 3, 'yes', 'why']

关于python - 交错 2 个长度不等的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19883826/

相关文章:

python - 如何在 wxPython 中管理动态、变化的主菜单?

Python 在遍历列表后删除列表中的一半元素

list - 输出似乎只测试列表中最后一个的差异函数

list - Netlogo:从列表列表中分配参数值

java - 在 for 循环 JAVA 中定义方法

python - python在for循环之前卡住列表吗?

python - 压缩串行 for 循环

python - 如何检查 JSON 文件是否不为空并正确从临时文件夹中的文件加载 JSON 数据?

python - 检查值是否位于区间内

python - 在 python 中打印越来越多的列表项