0

I am trying to create a tool that takes in a str of integers and a number of items per sublist, then produces a list object that has all the sublists nested inside of it. For example:

inputs:

str of ints: '1 2 3 4 5 6 7 8 9'
length of subsets:3

output: [[1,2,3],[4,5,6],[7,8,9]]

I am stuck as to how to create the sublists given the user input of sublist length. Here is my code so far....

b= []

def makeList():
    c = input("Drop your number list in here")
    d = input("How many per sublist?")
    newList = c.split()
    for i in newList:
        b.append(int(i))

this only leaves me with a list of integers. Is there a method that will do this easily? Or do I need to fight with a subloop iterating over the list, appending and popping as I go?

2 Answers2

0

Calculate chunk size:

chunk_sz = int(len(lst) / chunks) + 1

then chunk:

[lst[i:i+chunk_sz] for i in range(0, len(lst), chunk_sz)]
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
0
l = list(range(1, 10))
def split(l, size):
    return [l[i : i + size] for i in range(0, len(l), size)]
print(split(l, 3))

This outputs:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
blhsing
  • 91,368
  • 6
  • 71
  • 106