加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – interleaving 2个不等长的列表

发布时间:2020-12-20 10:33:46 所属栏目:Python 来源:网络整理
导读:参见英文答案 how to interleaving lists ????????????????????????????????????2个 我希望能够交错两个可能长度不等的列表.我有的是: def interleave(xs,ys): a=xs b=ys c=a+b c[::2]=a c[1::2]=b return c 这适用于长度相等或只是/ -1的列表.但是如果让我
参见英文答案 > how to interleaving lists ????????????????????????????????????2个
我希望能够交错两个可能长度不等的列表.我有的是:

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,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','bye',3,'no','yes','why']

使用itertools的roundrobin配方,此处不需要哨兵值:

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,'why']
>>> list(roundrobin(ys,xs))
['hi',1,'why']

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读