2014-10-28 105 views
1

我寫了一個函數,它獲取兩個參數:一個列表一個值出現在先前給出的列表(sep)中。該函數的目的是拆分給定的列表,並返回列表中的多個列表,而不用書寫功能的第二個參數中指定的值。所以def def_list([1,2,3,2,1],2)--->結果將會是[[1],[3],[1]]。分離的功能很好,但結果會保留分隔列表中函數(sep)的第二個值。我想不出如何解決這個問題。在此先感謝用分隔符分割列表

def split_list(l, sep): 
occurence = [i for i, x in enumerate(l) if x == sep] 
newlist=[] 
newlist.append(l[:occurence[0]]) 
for i in range(0,len(occurence)): 
    j=i+1 

    if j < len(occurence): 
    newlist.append(l[occurence[i]:occurence[j]]) 
    i+=1 
newlist.append(l[occurence[-1]:]) 


return newlist 

回答

2

如何:

def split_list(l, sep): 
    nl = [[]] 
    for el in l: 
     if el == sep: 
      nl.append([]) 
     else: 
      # Append to last list 
      nl[-1].append(el) 
    return nl 

或者用你的方法,通過使用OCCURENCES名單:

def split_list(l, sep): 
    # occurences 
    o = [i for i, x in enumerate(l) if x == sep] 
    nl = [] 
    # first slice 
    nl.append(l[:o[0]]) 
    # middle slices 
    for i in range(1, len(o)): 
     nl.append(l[o[i-1]+1:o[i]]) 
    # last slice 
    nl.append(l[o[-1]+1:]) 
    return nl 
+0

謝謝羊皮紙! :) – 2014-10-28 14:14:36

0

使用[列表(x)爲I,X列舉(l)如果x!= sep]

2

你可以將你的列表拆分成下面的列表理解和zip函數N:

>>> l=[1,2,3,2,1,8,9] 
>>> oc= [i for i, x in enumerate(l) if x == 2] 
>>> [l[i:j] if 2 not in l[i:j] else l[i+1:j] for i, j in zip([0]+oc, oc+[None])] 
[[1], [3], [1, 8, 9]] 

因此,對於你的函數:

def split_list(l, sep): 
occurence = [i for i, x in enumerate(l) if x == sep] 
return [l[i:j] if sep not in l[i:j] else l[i+1:j] for i, j in zip([0]+occurence, occurence+[None])]