首页 > 解决方案 > 返回列表,其中元素从轮流/python中的列表中获取

问题描述

我需要帮助将 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
    """

我尝试了什么:

# 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

标签: pythonpython-3.xlistloops

解决方案


看起来你想要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]

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]

推荐阅读