Ann*_*nna 6 python list nested-lists
我知道我可以使用以下方法将列表拆分为相同大小的子列表:
segment = len(list)//k
sub_lists = [list[i:i+segment] for i in range(0, len(list), segment)]
Run Code Online (Sandbox Code Playgroud)
但是,我不确定如何将长度为k ^ m的列表拆分为子列表,然后是其他子列表,直到每个子列表的长度为1.
例如:
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]]]]
Run Code Online (Sandbox Code Playgroud)
每当我试图循环这个时,我就会被打结,是否有捷径?
这本质上是你的代码:
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]]]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
93 次 |
| 最近记录: |