我想從串列中兩個 1 之間的 0 例如: l = [0,1,0,0,0,0,1,1,1,0,0,1,0,1,1,0]
我希望輸出為 [4, 2,1] 我如何在 python 中做到這一點
l = [0,1,0,0,0,0,1,1,1,0,0,1,0,1,1,0]
輸出是
[4,2,1]
uj5u.com熱心網友回復:
一種選擇使用熊貓:
l = [0,1,0,0,0,0,1,1,1,0,0,1,0,1,1,0]
s = pd.Series(l)
out = (s[s.eq(0)&s.cummax()&s.loc[::-1].cummax()]
.rsub(1).groupby(s.ne(0).cumsum()).sum()
.tolist()
)
使用純 python 和itertools.groupby:
from itertools import groupby
l = [0,1,0,0,0,0,1,1,1,0,0,1,0,1,1,0]
out = []
start = False
for k, g in groupby(l):
if k == 1:
if start:
out.append(count)
start = True
else:
count = len(list(g))
輸出:[4, 2, 1]
uj5u.com熱心網友回復:
使用方式略有不同- 使用第一個和最后一個之外的任何條目與我們無關itertools.groupby的事實1
from itertools import groupby
first_one = l.index(1) # index of the first "1"
last_one = len(l) - l[::-1].index(1) - 1 # index of the last "1"
out = [len(list(g)) for k, g in groupby(l[first_one:last_one], key=lambda x: x == 0) if k]
輸出
[4, 2, 1]
uj5u.com熱心網友回復:
這是純 Python 并且完美運行:
l = [0,1,0,0,0,0,1,1,1,0,0,1,0,1,1,0]
output = []
for i in range(len(l)):
if l[i] == 1:
zeros = 0
try:
while l[i 1 zeros] == 0:
zeros = 1
if zeros > 0:
output.append(zeros)
except:
break
print(output) #[4,2,1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/530239.html
標籤:Python列表二进制
上一篇:編譯makefile的問題
下一篇:創建具有一定數量列的資料框
