如何使用 RECURSION 对使用 python 的列表中的项目进行分组

How to use RECURSION to group items in a list using python

我正在尝试创建一个使用平面列表和 returns 列表的函数 lists/nested 列表,该列表基本上根据原始列表的值将它们的值组合在一起。

所以基本上

L = [ 1, 19, 5, 2, 22, 12 28]

如果我根据 10 L 的组将它们分组将成为

L = [[1, 2, 5], [12, 19], [22, 28]]

但是我必须使用递归来做到这一点。我有点迷路,不知道从哪里开始。如果我能得到一点帮助,我将不胜感激

def group_lists(L, pos): 
      if pos>=len(L):
        return none 
      else:
        if L[pos]<=10:
          return ?    
        elif 20>=L[pos]>10:
          return ? 
        else: 
          return ?    

您应该通过递归调用传递中间结果,然后在 运行 没有元素时 return 它。如果出于某种原因必须正好使用两个参数,请制作一个包装函数或使用 global 关键字。 (但是,我不建议在实践中使用 global。)

def group_lists(L, pos, result): 
  if len(L) <= pos:
    return result
  else:
    result[L[pos] // 10].append(L[pos])
    return group_lists(L, pos + 1, result)
    
L = [ 1, 19, 5, 2, 22, 12, 28]

print(group_lists(L, 0, [[], [], []]))

您可以尝试以下方法:

lst = [1, 19, 5, 2, 22, 12, 28]

def group_lists(lst):
    if not lst: # empty list
        return []
    output = group_lists(lst[1:]) # recursion
    while len(output) <= lst[0] // 10: # if not enough slots
        output.append([]) # make as many as needed
    output[lst[0] // 10].append(lst[0]) # append the item to the right slot
    return output

print(group_lists(lst)) # [[2, 5, 1], [12, 19], [28, 22]]

这将根据需要使用 while 循环自动添加插槽。如果您的输入类似于 [1, 21].

,它将生成空槽

这是一个每次递归调用添加一个子列表的版本:

>>> def group_lists(arr):
...     if isinstance(arr[-1], list):
...         return arr
...     i = sum(isinstance(sub, list) for sub in arr)
...     return group_lists(
...         arr[:i]
...         + [[n for n in arr[i:] if n // 10 == i]]
...         + [n for n in arr[i:] if n // 10 != i]
...     )
...
>>> group_lists([1, 19, 5, 2, 22, 12, 28])
[[1, 5, 2], [19, 12], [22, 28]]

您可以使用 collection 模块中的 defaultdict 结构,例如

from collections import defaultdict
def group_list(L, res=defaultdict(list)):
    if len(L) == 1:
        res[L[0] // 10].append(L[0])
        return
    if len(L) == 0:
        return
    group_list(L[:len(L) // 2])
    group_list(L[len(L) // 2:])
    return res

print(group_list([ 1, 19, 5, 2, 22, 12, 28]))

#defaultdict(<class 'list'>, {0: [1, 5, 2], 1: [19, 12], 2: [22, 28]})