根据Python中的计数器值将列表分为多个子列表

时间:2019-03-07 20:24:05

标签: python

我似乎找不到答案,但是我想基于一个计数器将一个列表分成多个较小的列表,以便新列表每次都包含相同的最大数量的值。

创建新的子列表后,我想继续逐步浏览原始列表,以基于下一个值创建新的子列表。

keywordList = ["24/7 home emergency", "6 month home insurance", "access cover", "access insurance",
              "are gas leaks covered by home insurance", "central heating breakdown cover", "trace & access",
              "trace and access", "trace and access costs"]
maxLength = 4

for c, items in enumerate(keywordList):
    if c < maxLength:
        #append items to new list here

预期的输出将是三个新列表,前两个长度为四个元素,最后一个长度为一个元素。但是,如果原始列表突然有100个元素,我们将获得25个新列表。

似乎有关于均匀分割原始列表的信息,但是没有关于预定值的信息。任何帮助表示感谢,谢谢。

2 个答案:

答案 0 :(得分:1)

编辑以反映您当前的问题:

keywordList = ["24/7 home emergency", "6 month home insurance", "access cover", "access insurance",
              "are gas leaks covered by home insurance", "central heating breakdown cover", "trace & access",
              "trace and access", "trace and access costs"]

leng = len(keywordList)
keywordList += [""] * ((leng//4+1)*4 - leng)
result = [[keywordList[i] for i in range(j, j+4)] for j in range(0, leng, 4)]
result[-1] = [e for e in result[-1] if e]

result

[['24/7 home emergency',
  '6 month home insurance',
  'access cover',
  'access insurance'],
 ['are gas leaks covered by home insurance',
  'central heating breakdown cover',
  'trace & access',
  'trace and access'],
 ['trace and access costs']]

此方法的想法是将keywordList用空字符串填充到4的倍数(可以是任意值),然后除以4。然后,清理空字符串的最后一个元素(或我们确定的任何内容)代表空对象)

答案 1 :(得分:0)

如果您想吐口水,请列出多个子列表,可以使用以下列表理解:

from itertools import repeat, zip_longest

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

iter_l = iter(l)

[list(filter(None.__ne__, i)) for i in zip_longest(*repeat(iter_l, 4))]
# [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]