Friday 15 March 2013

python - Splitting a list with a separator -



python - Splitting a list with a separator -

i have written function gets 2 arguments: list , one value nowadays in list given (sep). purpose of function split given list , homecoming multiple lists in list without value specified in sec argument of written fuction. def split_list([1,2,3,2,1],2) ---> result [[1],[3],[1]]. functionality of spliting result keeps sec value of function (sep) in separated lists. couldnt think of way how solve problem. in advance

def split_list(l, sep): occurence = [i i, x in enumerate(l) if x == sep] newlist=[] newlist.append(l[:occurence[0]]) 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]:]) homecoming newlist

how this:

def split_list(l, sep): nl = [[]] el in l: if el == sep: nl.append([]) else: # append lastly list nl[-1].append(el) homecoming nl

or method, using list of occurences:

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

python

No comments:

Post a Comment