在Python中基于计数器值将列表拆分为多个子列表

2024-06-01 13:28:55 发布

您现在位置: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个新的列表。你知道吗

似乎有关于平均拆分原始列表的信息,但没有关于预定值的信息。谢谢你的帮助。你知道吗


Tags: and答案信息元素home列表access计数器
2条回答

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

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。之后清除空字符串的最后一个元素(或者我们决定表示空对象的任何内容)

如果您想将列表划分为多个子列表,可以使用以下列表:

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]]

相关问题 更多 >