我编写了以下代码来递归拆分列表.它首先递归地分割左侧,直到并除非剩下一个元素.

代码:

def split(class_names):
 
  while len(class_names)>1:
    n=len(class_names)
    mid=n//2
    left=class_names[:mid]
    right=class_names[mid:]
    splits.append([left,right])
    class_names=left
    index=1
    split(left)
    class_names=right
  return splits
class_names=[1,2,3,4,5,6,7,8,9,10]
splits=[]
splits=split(class_names)

for ii in splits:
  print(ii)

输出:

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
[[1, 2], [3, 4, 5]]
[[1], [2]]
[[3], [4, 5]]
[[4], [5]]
[[6, 7], [8, 9, 10]]
[[6], [7]]
[[8], [9, 10]]
[[9], [10]]

问题:

                 [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
                            /\
                        0  /  \ 1
          [[1, 2], [3, 4, 5]]  [[6, 7], [8, 9, 10]]
                /\
            0  /  \ 1
       [[1], [2]]  [[3], [4, 5]]
Then the output should be like:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] = 0
[[1, 2], [3, 4, 5]] = 00
[[6, 7], [8, 9, 10]] = 01
[[1], [2]] = 000

推荐答案

您已经完成了递归,但需要在向左和向右遍历时跟踪索引.这是一种带有附加参数的方法,并重新编写为生成器:

def split(class_names, index='0'):
    if (n := len(class_names)) < 2:
        return
    mid = n // 2
    left, right = class_names[:mid], class_names[mid:]
    yield [left, right], index
    yield from split(left, index + '0')
    yield from split(right, index + '1')

class_names = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for node, index in split(class_names):
    print(f'{node} = {index}')

输出:

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] = 0
[[1, 2], [3, 4, 5]] = 00
[[1], [2]] = 000
[[3], [4, 5]] = 001
[[4], [5]] = 0011
[[6, 7], [8, 9, 10]] = 01
[[6], [7]] = 010
[[8], [9, 10]] = 011
[[9], [10]] = 0111

Python相关问答推荐

将每个关键字值对转换为pyspark中的Intramame列

使用子字符串动态更新Python DataFrame中的列

如何从不同长度的HTML表格中抓取准确的字段?

仅使用2种 colored颜色 创建热图

有什么方法可以修复奇怪的y轴Python matplotlib图吗?

根据多列和一些条件创建新列

单击Python中的复选框后抓取数据

创建带有二维码的Flask应用程序,可重定向到特定端点

请从Python访问kivy子部件的功能需要帮助

跟踪我已从数组中 Select 的样本的最有效方法

Odoo -无法比较使用@api.depends设置计算字段的日期

如何使用Google Gemini API为单个提示生成多个响应?

根据不同列的值在收件箱中移动数据

Django mysql图标不适用于小 case

Pandas 都是(),但有一个门槛

如何使用数组的最小条目拆分数组

如何在Python中并行化以下搜索?

pyscript中的压痕问题

Python Pandas获取层次路径直到顶层管理

手动设置seborn/matplotlib散点图连续变量图例中显示的值