返回列表,其中元素从turn / python中的列表中获取

1 python loops list python-3.x

我需要帮助将2个列表转换为元素从两个列表中依次提取的位置

def combine_lists(a, b):
    """
    combine_lists([1, 2, 3], [4]) => [1, 4, 2, 3]
    combine_lists([1], [4, 5, 6]) => [1, 4, 5, 6]
    combine_lists([], [4, 5, 6]) => [4, 5, 6]
    combine_lists([1, 2], [4, 5, 6]) => [1, 4, 2, 5, 6]
    :param a: First list
    :param b: Second list
    :return: Combined list
    """
Run Code Online (Sandbox Code Playgroud)

我试过的

# return a[0], b[0], a[1], b[1]
    combined_list = []
    for x, y in range (len(a), len(b)):
        combined_list = a[x], b[y]
    return combined_list
Run Code Online (Sandbox Code Playgroud)

yat*_*atu 5

看起来像你想要的itertools.zip_longest

from itertools import zip_longest

def combine_lists(*l):
    return [j for i in zip_longest(*l) for j in i if j]
Run Code Online (Sandbox Code Playgroud)
combine_lists([1, 2], [4, 5, 6])
# [1, 4, 2, 5, 6]

combine_lists([1, 2, 3], [4])
# [1, 4, 2, 3]

combine_lists([], [4, 5, 6])
# [4, 5, 6]
Run Code Online (Sandbox Code Playgroud)