【问题标题】:How do you sandwich lists together efficiently in python?你如何在python中有效地将列表夹在一起?
【发布时间】:2022-01-06 01:05:16
【问题描述】:

假设我有三个这样的列表:

list_of_lists = [ [1,2,3], [4,5,6], [7,8,9] ]

而不是正常连接它们,我想把它们夹在中间,就好像它们是三个不同的宾果球堆栈一样,我想从每个堆栈中依次取出一个球。

我不想得到一个 [1,2,3,4,5,6,7,8,9] 的列表,而是希望得到一个看起来更像这样的列表:

sandwiched_list = [1,4,7,2,5,8,3,6,9]

简单的逻辑是从每个列表中取出第一个数字,将其附加到一个新列表中,然后从旧列表中删除该数字并在列表列表中迭代重复。这可以正常工作,但速度非常慢。

还有其他选择吗?

【问题讨论】:

    标签: python list dataframe loops iteration


    【解决方案1】:

    你可以使用numpy:

    sandwiched_list = np.array(list_of_lists).flatten('F').tolist()
    #[1, 4, 7, 2, 5, 8, 3, 6, 9]
    

    【讨论】:

      【解决方案2】:

      使用 zip 按列表中的索引分组。

      list_of_lists = [ [1,2,3], [4,5,6], [7,8,9] ]
      grouped = list(zip(*list_of_lists))
      # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
      

      然后将其展平。

      import functools
      import operator
      functools.reduce(operator.iconcat, grouped, [])
      # [1, 4, 7, 2, 5, 8, 3, 6, 9]
      

      如需更多扁平化列表的方法,请查看this answer

      【讨论】:

        【解决方案3】:

        当列表长度相等时,这是一个 zip-splat 列表理解:

        >>> [n for splat in zip(*list_of_lists) for n in splat]
        [1, 4, 7, 2, 5, 8, 3, 6, 9]
        

        如果您需要处理长度不等的列表,您所描述的本质上是 itertools 文档中显示的 roundrobin recipe

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-30
          • 2023-03-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多