here_for_ever 2022-04-26 13:35 采纳率: 80%
浏览 48
已结题

递归之四个数的全排列如何保存到列表中

今天写代码有一块需要将四个数全排列,但是不知道如何把所有结果保存在一个列表中(用的是递归,照传统格式写的)
但是目前只能打印输出,不能保存

代码:
def per(pos,lt):
    lst = lt
    if pos == len(lst)-1:
        print(lst)
    else:
        for index in range(pos,len(lst)):
            lst[index],lst[pos] = lst[pos],lst[index]
            per(pos+1,lst)
            lst[index],lst[pos] = lst[pos],lst[index]
per(0,[1,2,3,4])

结果只能打印出来

[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 3, 2, 4]
[1, 3, 4, 2]
[1, 4, 3, 2]
[1, 4, 2, 3]
[2, 1, 3, 4]
[2, 1, 4, 3]
[2, 3, 1, 4]
[2, 3, 4, 1]
[2, 4, 3, 1]
[2, 4, 1, 3]
[3, 2, 1, 4]
[3, 2, 4, 1]
[3, 1, 2, 4]
[3, 1, 4, 2]
[3, 4, 1, 2]
[3, 4, 2, 1]
[4, 2, 3, 1]
[4, 2, 1, 3]
[4, 3, 2, 1]
[4, 3, 1, 2]
[4, 1, 3, 2]
[4, 1, 2, 3]

我曾尝试加上 listname.append(lst) 但无论放在哪都不对

我想要的结果

把结果返回到一个列表变量中

  • 写回答

3条回答 默认 最新

  • 溪风沐雪 2022-04-26 14:08
    关注

    在题主的基础上改一下,仅供参考:

    def per(pos,lt,lsts):
        lst = lt
        if pos == len(lst)-1:
            lsts.append(lst.copy())
        else:
            for index in range(pos,len(lst)):
                lst[index],lst[pos] = lst[pos],lst[index]
                per(pos+1,lst,lsts)
                lst[index],lst[pos] = lst[pos],lst[index]
    lsts = []
    per(0,[1,2,3,4],lsts)
    print(lsts)
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 5月4日
  • 已采纳回答 4月26日
  • 创建了问题 4月26日

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog