[PYTHON] How to sublist a list including the elements that are left over after dividing it into specific lengths

Thing you want to do

["a", "b", ... ,"z"]

When there is a list like ↑, I want to divide it into 5 characters such as a to e and f to j. Also, I would like to include the last remaining z in the list.

In other words

["a to e", "f to j", ..., "z"]

I would like to split it into sublists like.

Method

Queue all strings and retrieve every five. Also, by retrieving only non-empty cues, the last remaining element and beyond are ignored.

code

split.py


import queue

#Create a character list from a to z
chars = [chr(ord('a') + i) for i in range(26)]

#Create queue
q = queue.Queue()

#Insert character list in queue
for s in chars:
    q.put(s)

#List for storing split characters
subList = []

#Split character list
while not q.empty():

    #Temporarily save the split list
    splittedList = []  
    
    #Separate every 5
    for i in range(5):
        if not q.empty():
            splittedList.append(q.get())
    
    #Store in sublist
    subList.append(splittedList)

#output
print(subList)

result

>python split.py
[['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i', 'j'], ['k', 'l', 'm', 'n', 'o'], ['p', 'q', 'r', 's', 't'], ['u', 'v', 'w', 'x', 'y'], ['z']]

Postscript (2020/03/31)

We received a comment from @shiracamus. Thank you very much.

Recommended Posts

How to sublist a list including the elements that are left over after dividing it into specific lengths
[Python] Solution to the problem that elements are linked when copying a list
How to connect the contents of a list into a string
[Python] A program that rotates the contents of the list to the left
How to check in Python if one of the elements of a list is in another list
How to find the first element that matches your criteria in a Python list
How to list numbers by dividing them into n
Recursively get the Excel list in a specific folder with python and write it to Excel.
Get the number of specific elements in a python list
How to get the last (last) value in a list in Python
How to compare lists and retrieve common elements in a list
How easy is it to synthesize a drug on the market?
How to get a list excluding elements whose index is i ...?