Reputation: 125
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.
There seems to be information on splitting the original list evenly, but nothing on a predetermined value. Any help appreciated, thanks.
Upvotes: 0
Views: 394
Reputation: 5958
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
:
[['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)
Upvotes: 1
Reputation: 17911
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]]
Upvotes: 0