如何连续拆分列表并分离余数?



我将如何将列表一分为二,同时留下余数作为自己的"列表"?例如:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15]

不仅如此,还要继续将每个子列表减半以获得所需的结果:

[1, 2, 3], [4, 5, 6], [7], [8, 9, 10], [11, 12, 13], [14], [15]

下面的代码应该可以解决问题:

def splitList(array):
half = len(array) // 2 #find the halfway point
return (array[:half], #get the first half
array[half : half*2], #get the second half
array[half*2 : half*2 + len(array)%2] #get the remainder
)
array = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
splitList(array)
>> ['a', 'b', 'c'], ['d', 'e', 'f'], ['g']

然后根据需要重复多次:

array = [['a', 'b', 'c', 'd', 'e', 'f', 'g']]
for x in range(n):
newArray = []
for sub in array:
newArray += splitList(sub)
array = newArray
array = [e for e in array if e != []] #remove empty elements

您可以使用递归生成器:

def split_gen(lst, start=0, stop=None):
if stop is None:
stop = len(lst)
size = (stop - start)
if size < 4:
yield lst[start:stop]
return
half = size // 2
# two chunks of length half, plus an optional remainder
yield from split_gen(lst, start, start + half)
yield from split_gen(lst, start + half, start + (half * 2))
if size % 2 == 1:
yield lst[stop - 1:stop]

演示:

>>> list(split_gen([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]))
[[1, 2, 3], [4, 5, 6], [7], [8, 9, 10], [11, 12, 13], [14], [15]]

请注意,它不生成中间列表;它只是计算拆分的索引,并且只创建最终的子列表。

您可以使用两个函数,一个将初始列表拆分为部分列表,另一个函数对生成的列表进行递归调用,直到无法进一步拆分(len(sub-list) <= 3(,例如:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
def split_list(lst):
if len(lst) > 3:
n = len(lst) // 2  # integer division to get the size of the new sublists
new_list = list([lst[0:n]])  # append sublist 1
new_list.append(lst[n:n+n])  # append sublist 2
new_list.append(lst[len(lst)-len(lst) % 2:])  # get remainder and append to list
return split_sub(new_list)  
def split_sub(lst):
chk = 0
new_list = []
for item in lst:
if len(item) > 3:
n = len(item) // 2
new_list.append(list(item[0:n]))
new_list.append(item[n:n + n])
new_list.append(item[len(item) - len(item) % 2:])
else:
new_list.append(item)
chk += 1
if len(new_list) == chk:  # if this condition is met then all sub lists are of the size <= 3
return new_list
return split_sub(new_list)
print split_list(l)

第二个函数将继续运行,直到所有len(sub-list) <= 3这意味着它已完成拆分并将返回最终列表。

输出:

[[1, 2, 3], [4, 5, 6], [7], [8, 9, 10], [11, 12, 13], [14], [15]]

最新更新