python合并两个列表(偶数/奇数元素) [英] python merge two lists (even/odd elements)

查看:515
本文介绍了python合并两个列表(偶数/奇数元素)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出两个列表,我想将它们合并,以便第一个列表中的所有元素都被偶数索引(保留它们的顺序),而第二个列表中的所有元素都被奇数索引(也保留它们的顺序).下面的示例:

Given two lists, I want to merge them so that all elements from the first list are even-indexed (preserving their order) and all elements from second list are odd-indexed (also preserving their order). Example below:

x = [0,1,2]
y = [3,4]

result = [0,3,1,4,2]

我可以使用for循环来做到这一点.但是我想可能会有一种奇特的pythonic方式(使用一个鲜为人知的函数或类似的东西).有没有更好的解决方案,可以编写for循环?

I can do it using for loop. But I guess there could be a fancy pythonic way of doing this (using a less-known function or something like that). Is there any better solution that writing a for-loop?

我正在考虑列表推导,但是到目前为止还没有提出任何解决方案.

edit: I was thinking about list comprehensions, but didn't come up with any solution so far.

推荐答案

您可以轻松地做到:

for i,v in enumerate(y):
    x.insert(2*i+1,v)

这具有插入的优势,当插入被超过时,insert将使用最后一个索引.

this takes the advantage that insert will use the last index when it is overpassed.

一个例子:

x = [0,1,2,3,4,5]
y = [100, 11,22,33,44,55,66,77]
print x
# [0, 100, 1, 11, 2, 22, 3, 33, 4, 44, 5, 55, 66, 77]

这篇关于python合并两个列表(偶数/奇数元素)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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