python不等长编码有哪些_python – interleaving 2个不等长的列表

你可以在这里使用

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']

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

>>> list(roundrobin(ys, xs))

['hi', 1, 'bye', 2, 'no', 3, 'yes', 'why']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值