如何合并列表,但保持先前的列表顺序? [英] How does one merge a list, but maintain the previous lists order?

查看:49
本文介绍了如何合并列表,但保持先前的列表顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下方法合并后,我有了此列表.

I have this list once merged using the below gives me this output.

['description t2_HELP', 'description t2_1507', 'description t2_1189', 'description t2_5625', 'description None', 'description None', 'description None', 'description None', 'interface Gi3/0/13', 'interface Gi3/0/7', 'interface Gi1/0/11', 'interface Gi3/0/41']

但是,我希望在合并数据时保持该数据的顺序.因此示例列表集将如下所示.

I however want to maintain the order of that data when I merge it in. So example list set would look like this.

['interface Gi3/0/25','description None','description t2_2696','interface Gi1/0/29','description None','description t2_4148','interface Gi1/0/31','description None','description t2_4212','interface Gi2/0/31','description None','description t2_4271']

这是我合并列表的方式,

Here is how i'm merging the lists,

joinlist = data1 + data2 + data3

列表看起来像这样

data1 = ['interface Gi3/0/25','interface Gi1/0/29','interface Gi1/0/31','interface Gi2/0/31']
data2 = ['description None','description None','description None','description None']
data3 = ['description t2_2696','description t2_4148','description t2_4212','description t2_4271']

推荐答案

如果lists (zip) 的长度相等,其他建议也很好记住结果中的填充值 (zip_longest).

The other suggestions are fine if you have equal length lists (zip) or don't mind filler values in the result (zip_longest).

但是从逻辑上讲,您在这里要的是输入的循环,而不是压缩.通过展平,您会失去 zip 的配对方面,并且会因长度不均匀的输入而被其咬住.

But logically what you're asking for here is a round robining of inputs, not a zipping. By flattening, you lose the paired-up aspect of zip, and can get bitten by it for uneven length inputs.

> itertools 模块的 roundrobin 配方(单击代码链接,此处仅包含用法):

A more general solution to this problem is available with the itertools module's roundrobin recipe (click the link for code, I'm just including usage here):

joinlist = list(roundrobin(data1, data2, data3))

按顺序从每个输入中获取一个元素;如果一个输入比其他输入短,则在以后的回合中将其省略,而不会注入垃圾填充值或从较长的输入中丢失值.

That takes an element from each of the inputs in order; if one input is shorter than the others, it is omitted from later rounds without injecting garbage filler values or losing values from the longer input(s).

这篇关于如何合并列表,但保持先前的列表顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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