首页 > 解决方案 > 返回一个新列表,该列表交错两个列表,但有一个扭曲

问题描述

在此处输入图像描述

def back_interleave(first, second):

    if first == [] and second == []:
        return []
    elif first == []:
        return second[::-1]
    elif second == []:
        return first[::-1]
    else: 
        newlist = []
        for i in range(len(first)-1, 0,-1):
            newlist.append(first[i])
            newlist.append(second[i])
        for j in range(len(second)-len(first)-1,0,-1):
            newlist.append(second[i])
    return newlist

谁能告诉我我的代码对这个问题有什么问题。

标签: pythonlist

解决方案


我不确定您的代码有什么问题,但是第二个和第三个 if 语句似乎使用了原始问题禁止的内置列表反转功能。

我要做的是确定较长列表的长度,然后向后遍历两个列表。

def back_interleave(first, second):
    newlist = []
    # You want to iterate through the length of the longer list
    length = max(len(first), len(second))
    for x in range(length):
        # start appending elements from the back of the list
        index = -1*(x+1)
        if x < len(first):
            newlist.append(first[index])
        if x < len(second):
            newlist.append(second[index])
    return newlist

推荐阅读