2017-08-07 57 views
-6

我该如何去分割两个列表,还会留下一个余数作为自己的“列表”?例如:如何不断拆分列表并分离余数?

[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] 
+5

您是否尝试过什么自己了吗?什么时候分裂停止? –

+0

我试过将它分裂一次,但不知道从那里去哪里,只能设法分成相等的部分。当模式匹配底部列表时,分割应该停止,其中2个列表3后跟1个1的“列表”(因为我使用的所有列表都将有一个余数)。 –

+0

你可以[编辑]到你的问题。 –

回答

0

你可以使用递归发生器:

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]] 

注意它没有'不会产生中介名单;它只是计算分割的索引,并只创建最终的子列表。

0

可以使用两个函数,一个分裂初始列表部分列表,而另一个做所生成的列表上的递归调用,直到它不能例如被分割的任何进一步(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]]