用分隔符分割列表
问题描述:
我写了一个函数,它获取两个参数:一个列表和一个值出现在先前给出的列表(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
答
如何:
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
答
使用[列表(x)为I,X列举(l)如果x!= sep]
答
你可以将你的列表拆分成下面的列表理解和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])]
谢谢羊皮纸! :) – 2014-10-28 14:14:36