简体   繁体   English

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

[英]Split list in to multiple sublists based on counter value in Python

I can't seem to find an an answer for this, but I want to split a list in to multiple smaller lists based on a counter, so that the new list contains the same maximum number of values each time. 我似乎找不到答案,但是我想根据一个计数器将一个列表分成多个较小的列表,以便新列表每次都包含相同的最大数量的值。

Once I have created a new sublist, I want to continue stepping through the original list to create a new sublist based on the next values. 创建新的子列表后,我想继续逐步浏览原始列表,以基于下一个值创建新的子列表。

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

Expected output would be three new lists, first two four elements in length and the last one would be one element in length. 预期的输出将是三个新列表,前两个长度为四个元素,最后一个长度为一个元素。 But if the original list was suddenly to have 100 elements, we would get 25 new lists. 但是,如果原始列表突然有100个元素,我们将获得25个新列表。

There seems to be information on splitting the original list evenly, but nothing on a predetermined value. 似乎有关于均匀分割原始列表的信息,但是没有关于预定值的信息。 Any help appreciated, thanks. 任何帮助表示赞赏,谢谢。

Edit to reflect your current question: 编辑以反映您当前的问题:

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

The idea of this method is to pad the keywordList to a multiple of 4 with empty strings (could be anything) and then split by 4. After which clean the last element of empty strings (or whatever we decided to be representing empty object) 此方法的想法是将空列表(可以是任何东西)的keywordList为4的倍数,然后除以4。之后,清除空字符串的最后一个元素(或我们决定表示空对象的任何内容)

If you want to spit you list into multiple sublists you can use the following list comprehension: 如果您想吐出您的清单到多个子清单,您可以使用以下清单理解:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM