【问题标题】:Using Recursion to get lists of original list in Python returns error在 Python 中使用递归获取原始列表的列表返回错误
【发布时间】:2022-01-27 02:51:33
【问题描述】:

我被分配了一个使用递归的任务,以便任何给它的列表都说 p 将在所需的输出中返回,如最后所示,而不会干扰或改变 p 的内容。当我运行这个函数时,它说局部变量 (y) 是在没有赋值的情况下引用的,即 len(y)==0 但我已经在函数 init 之外分配了 y。有人可以帮助找出问题所在吗?

y=[] #To copy contents of x in it so that x is not modified
z=[] # To return it as a list required in the question
p=[1,2,3]

def inits(x):

    if len(y)==0 and len(z)==0:
        y=[i.copy for i in x] #Copying contents of x into x so that it remains unchanged

    if len(z)==len(x)+1: #z list is one plus x list because it has [] in it
        print(z)

    else:
        z.append(y.copy())
        if len(y)!=0: #This is done so that when y=[] it does not return error for y.pop(-1)
            y.pop(-1)
        inits(x)

inits(p)

#Desired Output
[[1,2,3],[1,2],[1],[]]

【问题讨论】:

    标签: python-3.x list recursion


    【解决方案1】:

    如果您不需要最后一个空元素,请随意删除 else 块。
    你的 y 变量对我来说也不需要

    z = []  # To return it as a list required in the question
    
    def foo(param):
        if len(param):
            z.append([i for i in param])
            foo(param[0:-1])
        else:
            z.append([])
    
    
    foo([1, 2, 3])
    print(z)
    
    [[1, 2, 3], [1, 2], [1], []]
    

    【讨论】:

    • Bravo,这太棒了,但我仍然对 python 生成的错误感到困惑。我已经分配了 y 和 z 外部函数,但它仍然给出错误,为什么?
    • @AzhanAhmed 好吧,您至少有两个错误:您必须在函数中使用global y,第二个i.copy 整数副本也是错误的。
    猜你喜欢
    • 2020-02-23
    • 1970-01-01
    • 2012-12-18
    • 2021-08-21
    • 2020-01-22
    • 1970-01-01
    • 2021-11-02
    • 2014-01-18
    相关资源
    最近更新 更多