【问题标题】:Return list where the elements are taken from lists in turns/python返回列表,其中元素从轮流/python中的列表中获取
【发布时间】:2020-01-25 18:50:53
【问题描述】:

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

【问题讨论】:

  • 看来您基本上想要roundrobin 记录的here

标签: python python-3.x list loops


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我的回答不像@yatus那么简单,但是你可以使用以下:

    def combine_lists(a, b):
        combined_list = []
        for e_a, e_b in zip(a, b):
            combined_list.append(e_a)
            combined_list.append(e_b)
    
        len_a = len(a)
        len_b = len(b)
    
        if len_a == len_b:
            return combined_list
        if len(a) > len_b:
            return combined_list + a[len_b:]
        # this means len_b is greater than len_a
        return combined_list + b[len_a:]
    

    >>> 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]
    

    【讨论】:

      【解决方案3】:

      我认为这可行:

      [x for x in itertools.chain.from_iterable(itertools.zip_longest(a, b)) if x is not None]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-31
        • 2012-04-04
        • 1970-01-01
        • 2020-04-23
        • 2016-01-14
        • 1970-01-01
        • 2021-07-10
        相关资源
        最近更新 更多