Skip to main content
 首页 » 编程设计

python之返回列表,其中元素依次从列表中获取/python

2025年05月04日16shangdawei

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

请您参考如下方法:

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