我正在尝试编写一个创建二分分组列表 f 的函数。前任。如果我的输入如下:
[a, b, c, d, e, f, g, h]
我想选择随机整数,它会一次又一次地递归地将它分成更小的子列表,直到子列表的长度最大为二,比如:
[[a, [b, c]], [d, [[e, f], [g, h]]]]
这是我到目前为止所得到的,但仍然给了我 类型错误(列表索引必须是整数或切片,而不是列表):
def split_list(l):
if l.__len__() > 2:
pivot = np.random.random_integers(0, l.__len__() - 1)
print(pivot, l)
l = [RandomTree.split_list(l[:pivot])][RandomTree.split_list(l[pivot:])]
return l
我被卡住了,如果有任何建议,我将不胜感激。
最佳答案
您的问题对所使用的数据类型不是很清楚,并且似乎使用了一种非传统类型的递归(可能作为类的一部分)。对于错误向下滚动一点。
我冒昧地稍微修改了代码并使用了普通的 random
库,所以你正在寻找的可能看起来像
import random # at the module-declaration part of your program
def split_list (l):
if len(l) < 2:
return l
pivot = random.randint(1, len(l) - 1)
return [RandomTree.split_list(l[:pivot]) + RandomTree.split_list(l[pivot:])]
我们在单个元素列表上停止递归,如果我们还没有停止,则进一步应用递归,使用从可能范围中提取的随机索引(注意 random.randint
生成具有指定边界的索引包括)。
您的错误是没有在返回值的两个部分之间使用任何连接运算符。
[A][B]
不会连接两个列表,而是尝试从 A< 索引
,这是一种类型错误的用法。B
(在您的情况下)中给出的列表
因此您可以使用原始函数(使用已弃用的 numpy
random)作为
def split_list(l):
if l.__len__() > 2:
pivot = np.random.random_integers(0, l.__len__() - 1)
l = [RandomTree.split_list(l[:pivot])] + [RandomTree.split_list(l[pivot:])]
return l
关于python - 递归和随机分组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48360056/