【问题标题】:Python - Creating a new list using existing lists of the same length? [duplicate]Python - 使用相同长度的现有列表创建新列表? [复制]
【发布时间】:2013-03-26 14:25:18
【问题描述】:

"给定长度相同的列表list1和list2,创建一个新列表,其中包含list1的第一个元素,后跟list2的第一个元素,后跟list1的第二个元素,后跟list2的第二个元素list2,依此类推(换句话说,新列表应该由 list1 和 list2 的交替元素组成)。例如,如果 list1 包含 [1, 2, 3] 而 list2 包含 [4, 5, 6],那么新的列表应包含 [1, 4, 2, 5, 3, 6]。将新列表与变量 list3 关联。"

    list1 = []
    list2 = []
    list3 = []
    for i in range(len(list3)):
        list3.append(list1)
        list3.append(list2)

我很确定这是大错特错。我应该改进什么?顺便说一句,我认为这必须包括 len 和 range。

【问题讨论】:

  • 好吧,你不会进入你的 for 循环,因为当你到达那里时 len 为 0......这是一回事
  • 很确定?你运行你的代码了吗?

标签: python


【解决方案1】:

我会用列表理解来做,而不是用lenrange。例如:

>>> list1 = [1, 2, 3]
>>> list2 = ['a', 'b', 'c']
>>> zip(list1, list2)
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> [x for pair in zip(list1, list2) for x in pair]
[1, 'a', 2, 'b', 3, 'c']

【讨论】:

    【解决方案2】:
    >>> from itertools import chain
    >>> list1 = [1, 2, 3]
    >>> list2 = [4, 5, 6]
    >>> list(chain.from_iterable(zip(list1, list2)))
    [1, 4, 2, 5, 3, 6]
    

    【讨论】:

      【解决方案3】:
      list1 = [1, 2, 3]
      list2 = [4, 5, 6]
      list3 = []
      
      for x1, x2 in zip(list1, list2):
          list3.extend([x1, x2])
      

      【讨论】:

        【解决方案4】:

        请看下面的sn-p,也许会有所帮助

        >>> list1 = [1,2,3]
        >>> list2 = [4,5,6]
        >>> list3 = []
        >>> for i in range(len(list1)):
        ...     list3.append(list1[i])
        ...     list3.append(list2[i])
        ...
        >>> list3
        [1, 4, 2, 5, 3, 6]
        

        【讨论】:

        • 在我看来,for x1, x2 in zip(list1, list2): 会更好。
        • @wim 是的,这也可以。感谢您指出。
        猜你喜欢
        • 2017-02-07
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 2018-11-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多