【问题标题】:How to split the list into chunks with equal size and if the list is odd I want to add the chunk the previous chunk如何将列表拆分为大小相等的块,如果列表是奇数,我想将块添加到前一个块
【发布时间】:2019-04-22 14:14:31
【问题描述】:

如果数据集包含 n=385,现在我想拆分每个块包含 95、95、95、95、5 之类的点。现在我想将最后 5 个点添加到前一个块中

我在 jupyter notebook 上运行

def chunks(l, n):
   return [l[i:i+n] for i in range(0, len(l), n)]

slice =chunks(dataframe, int(len(dataframe)/4))

我希望输出大小相等

【问题讨论】:

  • 对于chunks([1,2,3,4,5,6,7,8,9,10],3),你的输出是[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]],我将最后一个元素附加到倒数第二个子列表中吗?

标签: python list function


【解决方案1】:

您可以添加一个条件,如果最后一个块不是您想要的长度,该函数会将其添加到前一个块并仅在该索引之前返回。例如:

def chunks(l, n):
  foo = [l[i:i+n] for i in range(0, len(l), n)]
  if len(foo[-1]) != n:
    foo[-2]+= foo[-1]
    return foo[:-1]
  else:
    return foo


l = [i for i in range(100)]

chunks = chunks(l, 6)
print(chunks)

输出:

[[0, 1, 2, 3, 4, 5], 
 [6, 7, 8, 9, 10, 11],
...
 [84, 85, 86, 87, 88, 89], 
 [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]]

【讨论】:

    【解决方案2】:
    def chunks (l, n):
      r = [l]
      while len (r [-1]) >= 2 * n:
        r [-1:] = [r [-1][:n], r [-1][n:]]
      return r
    

    【讨论】:

      【解决方案3】:

      您可以通过添加最后一个子列表,然后删除最后一个子列表来更新现有代码中列表的倒数第二个子列表,前提是最后一个子列表的大小不是 n,即块大小

      def chunks(l, n):
         li = [l[i:i+n] for i in range(0, len(l), n)]
         #Add the second last sublist to the last sublist
         #Only if the last sublist is not of size n
         if len(li[-1]) != n:
              li[-2] += li[-1]
              #Remove the last element
              li.pop(-1)
         return li
      

      输出将是

      print(chunks([1,2,3,4,5,6,7,8,9],3))
      #[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
      print(chunks([1,2,3,4,5,6,7,8,9,10],3))
      #[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
      

      【讨论】:

      • 如果nlen(l) 的倍数,这将达不到目的
      猜你喜欢
      • 2023-01-07
      • 1970-01-01
      • 1970-01-01
      • 2022-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      相关资源
      最近更新 更多