交错2个长度不等的列表 [英] interleaving 2 lists of unequal lengths

查看:33
本文介绍了交错2个长度不等的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to be able to interleave two lists that could potentially be unequal in length. What I have is:

  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= [""bye","no","yes","why"] 这个消息出现:

This works great with lists that either equal in length or just +/-1. But if let's say xs=[1,2,3] and ys= [""bye","no","yes","why"] this message appears:

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

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

How do I fix this with using indexing? or do I have to use for loops? what I want is to have the extra values just appear at the end.

推荐答案

可以使用heapq.merge:

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

import heapq
interleaved = [v for i, v in heapq.merge(*[enumerate(el) for el in (xs, ys)])]
# [1, 'hi', 2, 'bye', 3, 'no', 'yes', 'why']

这避免了对哨兵值和扁平化的需要.

This avoids the need for a sentinel value and flattening.

改用 roundrobin recipe 来更有效地实现这一目标,而无需项目具有可比性.

Use the roundrobin recipe instead to achieve this more effectively without having items be comparable.

这篇关于交错2个长度不等的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆