【问题标题】:Splitting a list of lists, each containing x items, into a list of twice as many lists, each containing x/2 items将列表列表拆分为列表,每个列表包含 x 项,列表的数量是列表的两倍,每个列表包含 x/2 项
【发布时间】:2019-09-29 18:54:02
【问题描述】:

我正在尝试将一个列表列表拆分为一个列表,每个列表包含 n 个项目,列表的数量是列表的两倍,每个列表包含 n/2 个项目。

例如

  list_x = [[list_a], [list_b]]

  list_a = ['1','2','3','4','5','6']
  list_b = ['7','8','9','10','11','12']

我需要:

list_x2 = [[list_a2], [list_b2], [list_c2], [list_d2]]

地点:

list_a2 = ['1','2','3']
list_b2 = ['4','5','6']
list_c2 = ['7','8','9']
list_d2 = ['10','11','12']

我尝试过: All possibilities to split a list into two lists - 但希望能深入了解如何将一些提到的解决方案扩展到“带有列表的列表”场景。

任何帮助表示赞赏。

【问题讨论】:

    标签: python python-3.x list split


    【解决方案1】:

    您可以使用列表推导:

    list_x = [['1', '2', '3', '4', '5', '6'], ['7', '8', '9', '10', '11', '12']]
    n = 2
    list_x2 = [l[i: i + len(l) // n] for l in list_x for i in range(0, len(l),  len(l) // n)]
    

    【讨论】:

      【解决方案2】:

      没有人提供numpy 解决方案...这可能不是我们所要求的,但它很好;)

      list_a = ['1','2','3','4','5','6']
      list_b = ['7','8','9','10','11','12']
      list_x = [list_a, list_b]
      
      a = np.array(list_x)
      w, h = a.shape
      a.shape = w*2, h//2
      
      list_x2 = a.tolist()
      

      【讨论】:

        【解决方案3】:

        试试这个:

        list_x = [list_a, list_b]
        #[['1', '2', '3', '4', '5', '6'], ['7', '8', '9', '10', '11', '12']]
        n = 3
        list_x2 = [[l[3*i:3*j+3] for i,j in zip(range(len(l)//n), range(len(l)//n))] for l in list_x]
        

        输出

        [[['1', '2', '3'], ['4', '5', '6']], [['7', '8', '9'], ['10', '11', '12']]]
        

        【讨论】:

          【解决方案4】:
          from operator import add
          from functools import reduce
          
          addlists = lambda l: reduce(add, l)
          
          list_a = ['1','2','3','4','5','6']
          list_b = ['7','8','9','10','11','12']
          list_x = [list_a, list_b]
          
          k = len(list_a) // len(list_x)
          
          joined = addlists(list_x)
          res = list(map(list, zip(*([iter(joined)]*k))))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-05-26
            • 1970-01-01
            • 1970-01-01
            • 2021-06-04
            • 1970-01-01
            相关资源
            最近更新 更多