以交错方式组合两个Python列表 [英] Combining two Python lists in an interleaved manner

查看:87
本文介绍了以交错方式组合两个Python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想插入两个列表.例如:

I want to interleave two lists. For example:

arr1 = [1,2,3,4,5,6]
arr2 = [9,8,7,6]

我不喜欢这样的输出

[1,9,2,8,3,7,4,6,5,6]

我创建了以下脚本,但是由于某些原因它无法正常工作:

I have created the following script, but it's not working for some reason:

arr1 = [1,2,3,4,5,6]
arr2 = [9,8,7,6]
x = 0

for a in arr2:
    x = x + 2
    arr1.insert(x, a)

我要去哪里错了?我不是在寻找随机混洗.我正在使用python2.x

Where am I going wrong? I am not looking for random shuffling. I am using python2.x

推荐答案

我想出了另一种方法,无需导入.

I have figured out a different way to do this, without imports.

mylist = []
a = [1,2,3,4,5,6]
b = [9,8,7,6]
for x in range(max(len(a), len(b))):
    if x < len(a):
        mylist.append(a[x])
    if x < len(b):
        mylist.append(b[x])

这篇关于以交错方式组合两个Python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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