I know that I can split a list into sub-lists of equal size using:
segment = len(list)//k
sub_lists = [list[i:i+segment] for i in range(0, len(list), segment)]
However I'm not sure how to split a list of length k^m into sub-lists, then further sub-lists until each sub-list has length of 1.
For example:
k = 2
list = [1, 2, 3, 4, 5, 6, 7, 8]
list = [[1, 2, 3, 4], [5, 6, 7, 8]]
list = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
list = [[[[1], [2]], [[3], [4]]], [[[5], [6]], [[7], [8]]]]
Whenever I've tried to loop this I get tied in knots, is there a short-cut?
To split the elements of a list in Python: Use a list comprehension to iterate over the list. On each iteration, call the split() method to split each string. Return the part of each string you want to keep.
Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
Usually, we use a comma to separate three items or more in a list. However, if one or more of these items contain commas, then you should use a semicolon, instead of a comma, to separate the items and avoid potential confusion.
This is essentially your code:
def split_list(input_list, segments):
if len(input_list) == 1:
return input_list
segment_length = len(input_list) // segments
return [split_list(input_list[i:i+segment_length], segments)
for i in range(0, len(input_list), segment_length)]
>>> split_list([1, 2, 3, 4, 5, 6, 7, 8], 2)
[[[[1], [2]], [[3], [4]]], [[[5], [6]], [[7], [8]]]]
def sub_k_list(a, k):
p = len(a) // k
return a if not p else [sub_k_list(a[:p], k), sub_k_list(a[p:], k)]
k = 2
a = [1, 2, 3, 4, 5, 6, 7, 8]
print(sub_k_list(a, k))
Result:
[[[[1], [2]], [[3], [4]]], [[[5], [6]], [[7], [8]]]]
Edit: remove the if ...
def sub_k_list(a, k):
p = len(a) // k
return a * (not p) or [sub_k_list(a[:p], k), sub_k_list(a[p:], k)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With