我编写了一个函数,该函数具有两个参数:一个列表和一个在先前给定的列表中存在的值(sep)。该函数的目的是拆分给定列表,并在列表中返回多个列表,而这些列表中没有在编写函数的第二个参数中指定的值。因此,使用def split_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
或使用您的方法,通过使用事件列表:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句