我有一個列表,說拆分列表爲單獨列出[Python的]
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]]
我有一個列表,說拆分列表爲單獨列出[Python的]
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]]
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]]
如果沒有重複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
嘿,你和我已經回答了這個問題。 :-) – DSM 2014-11-08 22:22:52
@DSM:真的嗎? /我運行並檢查歷史 – inspectorG4dget 2014-11-08 22:24:08
難道你不能只使用'bool'而不是'lambda x:x!= 0'? – khelwood 2014-11-08 22:25:22