【问题标题】:Recursive function in removing occurence in list python删除列表python中出现的递归函数
【发布时间】:2016-01-08 23:21:10
【问题描述】:
def remove_all1(x,s):
    def loop(x,s,ss):
        while s!=[]:
            if x == s[0]:
                return loop(x,s[2:],ss+[s[1]])
            else:
                return loop(x,s[1:],ss+[s[0]])
        return ss
    return loop(x,s,[])

这是我用递归尾函数制作的,用于删除递归值 x 和 if :

print(remove_all1(3,[4,3,5,6,3,2,1]))

我会得到:

[4,5,6,2,1]

我想要的确切结果。但是对于这里的递归函数:

def remove_all0(x,s):
    while s!=[]:
        if x == s[0]:
            ss = [s[1]] + remove_all0(x,s[2:])
            return ss 
        else:
            s1 = [s[0]] + [remove_all0(x, s[1:])]
            return s1 
    if s==[]:
        return s
print(remove_all0(3,[4,3,5,6,3,2,1]))

我不会得到相同的结果。相反,我得到了:

[4, [5, 6, [2, 1, []]]]

为什么会这样?

【问题讨论】:

  • remove_all0 返回一个列表,当您递归调用它时,您将其包装在另一个列表中
  • 我认为这篇文章可能也很有趣stackoverflow.com/questions/1157106/… 它展示了如何有效地从 Python 列表中删除所有出现的项目。

标签: python list recursion removeall


【解决方案1】:

问题出在else 子句中,当您包装来自remove_all0 的返回值时,它是一个列表,并使其成为包含该列表的列表。只需删除那些方括号,你就会得到你想要的结果:

def remove_all0(x,s):
    while s!=[]:
        if x == s[0]:
            ss = [s[1]] + remove_all0(x,s[2:])
            return ss
        else:
            s1 = [s[0]] + remove_all0(x, s[1:])
            return s1
    if s==[]:
        return s
print(remove_all0(3,[4,3,5,6,3,2,1]))

给予

[4, 5, 6, 2, 1]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多