簡體   English   中英

遞歸函數在python中拆分列表

[英]Recursive function to split a list in python

我編寫了一個函數,以獲取任意值的列表並將其按特定值拆分為子列表。 基本上,我想獲取一個列表並在所有出現特定值時將其拆分,以返回子列表的列表。 我認為最簡單的方法是通過如下的遞歸函數。

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], [])))

我敢肯定有辦法解決這個問題,但是我嘗試了盡可能多的組合,但似乎沒有一種適合我。

我不認為當您可以使用itertools.groupby時,遞歸是最簡單的方法:

from itertools import groupby

lst = [list(g) for k, g in groupby(P, lambda x: x is not None) if k]
print(lst)
# [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10, 11]]

另外請記住,遞歸並不便宜

正如某人已經指出的那樣,遞歸函數可能不是此特定任務的最佳方法(至少在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))

==>

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']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM