Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split sub-lists into sub-lists k times? (Python)

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?

like image 609
Anna Avatar asked Jan 14 '16 20:01

Anna


People also ask

How do you split a nested list in Python?

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.

Can you split () a list in Python?

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.

How do you separate multiple lists?

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.


2 Answers

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]]]]
like image 78
Finwood Avatar answered Oct 09 '22 23:10

Finwood


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)]
like image 37
mementum Avatar answered Oct 10 '22 01:10

mementum