用于在python中拆分列表的递归函数

用于在python中拆分列表的递归函数,python,recursion,Python,Recursion,我编写了一个函数,用于获取任意值的列表,并以特定值将其拆分为子列表。基本上,我希望获取一个列表,并在某个特定值出现时将其拆分,返回一个子列表列表。我认为最简单的方法是通过递归函数,如下所示 def recsplit(L, val): if L.count(val)==0: # If there are no occurrences, return the whole list return L elif L.index(val)==0: # If the valu

我编写了一个函数,用于获取任意值的列表,并以特定值将其拆分为子列表。基本上,我希望获取一个列表,并在某个特定值出现时将其拆分,返回一个子列表列表。我认为最简单的方法是通过递归函数,如下所示

def recsplit(L, val):
    if L.count(val)==0: # If there are no occurrences, return the whole list
        return L
    elif L.index(val)==0: # If the value is the first element, return everything else
        return recsplit(L[1:],val)
    else: # Otherwise, split at the first instance of value
        return L[:L.index(val)], recsplit(L[L.index(val)+1:],val)
函数应该像这样工作:

>>> P = [1,2,3,4,5,None,None,6,7,8,None,9,10,11,None]
>>> recsplit(P,None) 
[[1,2,3,4,5],[6,7,8],[9,10,11]]
不幸的是,我得到了以下输出:

([1, 2, 3, 4, 5, 6, 7], ([8, 9, 10, 11], ([12, 13, 14, 15], [])))

我确信有办法解决这个问题,但我已经尝试了尽可能多的组合,但似乎没有一种适合我。

我不认为递归是最简单的方法,如果可以使用:


还请记住,递归并不便宜。

正如有人已经指出的,递归函数可能不是执行此特定任务的最佳方式(至少在python中是如此)。但是,既然您提出了要求,下面是使用递归调用生成您期望的确切输出的代码

def recsplit(L, val, out=[[]]):
    if L == []:
        return out
    elif L[0] == val and out[-1] != [] and L[1:].count(val) != len(L[1:]):
        return recsplit(L[1:], val, out + [[]])
    elif L[0] != val and L[0] is not None:
        return recsplit(L[1:], val, out[:-1] + [out[-1] + [L[0]]])
    else:
        return recsplit(L[1:], val, out)

P = [1,2,3,4,5,None,None,6,7,8,None,9,10,11,None]
P1 = [1,2,None,3,4,5,None,"x","x",None,6,7,8,"x",9,10,11,None,"x","x"]  
print("Subs of P by None =", recsplit(P,None))
print("Subs of P1 by x =", recsplit(P1,"x"))
print("Subs of P1 by None =", recsplit(P1,None))
==>

你必须使用递归吗?
def recsplit(L, val, out=[[]]):
    if L == []:
        return out
    elif L[0] == val and out[-1] != [] and L[1:].count(val) != len(L[1:]):
        return recsplit(L[1:], val, out + [[]])
    elif L[0] != val and L[0] is not None:
        return recsplit(L[1:], val, out[:-1] + [out[-1] + [L[0]]])
    else:
        return recsplit(L[1:], val, out)

P = [1,2,3,4,5,None,None,6,7,8,None,9,10,11,None]
P1 = [1,2,None,3,4,5,None,"x","x",None,6,7,8,"x",9,10,11,None,"x","x"]  
print("Subs of P by None =", recsplit(P,None))
print("Subs of P1 by x =", recsplit(P1,"x"))
print("Subs of P1 by None =", recsplit(P1,None))
Subs of P by None = [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10, 11]]
Subs of P1 by x = [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10, 11]]
Subs of P1 by None = [[1, 2], [3, 4, 5], ['x', 'x'], [6, 7, 8, 'x', 9, 10, 11], ['x', 'x']]