AustinB - 1 year ago 115
Python Question

# How can I split an integer into a list of n length evenly in Python 3.5?

I need to be able to split an integer into a list of n-length evenly.

For example n = 4,

12 -> [0, 0, 1, 2]
1234 -> [1, 2, 3, 4]
12345 -> [1, 2, 3, 45]
123456 -> [1, 2, 34, 56]
1234567 -> [1, 23, 45, 67]
12345678 -> 12, 34, 56, 78]
123456789 -> [12, 34, 56, 789]

I'm sure I went overkill with the number of examples I have given, but it'll help get the point across.

The code that I have used in the past to split items into lists is:

def split(s, chunk_size):
a = zip(*[s[i::chunk_size] for i in range(chunk_size)])
return [''.join(t) for t in a]

but this code only breaks into n-chunks. (Code from StackOverflow, I don't remember the exact post, sorry).

Thanks for the help.

def split(seq, n):
"""Partitions `seq` into `n` successive slices of roughly equal size.

The sizes of each yielded slice shall differ by at most one.
"""
q, r = divmod(len(seq), n)
start = 0

for i in range(n):
size = q + (i < r)
yield seq[start : start + size]
start += size

It basically works the same way as this popular answer, except it evenly distributes the remainder into each of the n slices.

Unfortunately, this will distribute towards the head of the list. To tweak it for your case, you need to change size = q + (i < r) to something like:

size = q + (i >= (n - r))

With this change, the following:

print(list(split('1234', 4)))
print(list(split('12345', 4)))
print(list(split('123456', 4)))
print(list(split('1234567', 4)))
print(list(split('12345678', 4)))
print(list(split('123456789', 4)))

prints:

['1', '2', '3', '4']
['1', '2', '3', '45']
['1', '2', '34', '56']
['1', '23', '45', '67']
['12', '34', '56', '78']
['12', '34', '56', '789']