我有一个清单,说
listx = [1, 2, 0, 5, 2, 3, 0, 3, 4, 2, 3, 5, 6, 0, 4]
如何将列表拆分为不包含0的连续部分?例如,此列表将拆分为
separated = [[1, 2], [5, 2, 3], [3, 4, 2, 3, 5, 6], [4]]
答案 0 :(得分:3)
import itertools
In [69]: L = [1, 2, 0, 5, 2, 3, 0, 3, 4, 2, 3, 5, 6, 0, 4]
In [70]: [list(i[1]) for i in itertools.groupby(L, bool) if i[0]]
Out[70]: [[1, 2], [5, 2, 3], [3, 4, 2, 3, 5, 6], [4]]
答案 1 :(得分:0)
如果没有重复0's
:
listx = [1, 2, 0, 5, 2, 3, 0, 3, 4, 2, 3, 5, 6, 0, 4]
final = [[]]
for ele in listx:
final[-1].append(ele) if ele else final.append([])
print(final)
[[1, 2], [5, 2, 3], [3, 4, 2, 3, 5, 6], [4]]
如果您重复0's
:
def split_l(l):
final = [[]]
for ele in l:
final[-1].append(ele) if ele else final.append([])
return filter(None, final)
In [146]: timeit split_l(L)
100 loops, best of 3: 19.6 ms per loop
In [147]: timeit [list(i[1]) for i in itertools.groupby(L, bool) if i[0]]
10 loops, best of 3: 33.8 ms per loop