小编FD *_*GOD的帖子

递归查找列表的所有组合

问题陈述

我想从我的列表中获取所有可能的组合(包括空列表)。

到目前为止我的代码是:

def combination(l):
    result = []
    for item in range(len(l)):
        cut_list = l[:item] + l[item + 1:]
        if len(cut_list) > 1:
            combination(cut_list)
        elif len(cut_list) == 1:
            result += cut_list
    return result


print(combination([1, 2, 3]))
Run Code Online (Sandbox Code Playgroud)

我的输出是一个空列表

[]
Run Code Online (Sandbox Code Playgroud)

我想要这个输出:

[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
Run Code Online (Sandbox Code Playgroud)

我很确定我的退货有些不对劲。

非常感谢任何帮助。

python recursion combinations return list

1
推荐指数
1
解决办法
8323
查看次数

标签 统计

combinations ×1

list ×1

python ×1

recursion ×1

return ×1