Python 获取序列为0或1的二进制列表的开始和结束1的索引
我有一个python列表,其中包含二进制信息,可以是1序列,也可以是0序列,例如:Python 获取序列为0或1的二进制列表的开始和结束1的索引,python,Python,我有一个python列表,其中包含二进制信息,可以是1序列,也可以是0序列,例如: event = [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1] 如何存储起始1和结束1的索引值 例如: event = [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1
event = [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1]
如何存储起始1和结束1的索引值
例如:
event = [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1]
如果事件=[0,0,1,1,1,1,0,0,1,1,1,1]
则结果=[2,5,8,11]
EDIT2我意识到理想的结果应该是result\u start=[2,8]result\u end=[5,11],就像懒散的解决方案一样,这样我们就知道了一个1的位置。例如,event=[0,0,1,1,0,1]将为最后一个1生成错误的列表。谢谢大家的努力
EDIT1:我需要第一个和最后一个1的索引,但从第一个到最后一个1
我尝试按如下方式编写代码:
k=False
j=0
result=[]
for i in event:
if i==1:
k=True
result.append(k)
else:
k=False
我知道你真正想要的是什么,你可以这样做:
result = []
is_one = False
for i in range(len(event)):
if not is_one and event[i] == 1: #Starting chain of ones
is_one = True
result.append(i)
elif is_one and event[i] == 0: #Finished a chain of ones
is_one = False
result.append(i-1)
if is_one: #The list finished with a chain of ones
result.append(len(event)-1)
我知道你真正想要的是什么,你可以这样做:
result = []
is_one = False
for i in range(len(event)):
if not is_one and event[i] == 1: #Starting chain of ones
is_one = True
result.append(i)
elif is_one and event[i] == 0: #Finished a chain of ones
is_one = False
result.append(i-1)
if is_one: #The list finished with a chain of ones
result.append(len(event)-1)
编辑:
还要查找从索引0开始的范围
创建了one\u ranges
函数,该函数返回(开始、结束)
元组列表
>>> event = [0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1]
>>> event = [0] + event + [0]
>>> [i-1 for i in xrange(1,len(event)-1) if event[i]==1 and (event[i+1]==0 or event[i-1]==0)]
[2, 5, 8, 11]
编辑:
还要查找从索引0开始的范围
创建了one\u ranges
函数,该函数返回(开始、结束)
元组列表
>>> event = [0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1]
>>> event = [0] + event + [0]
>>> [i-1 for i in xrange(1,len(event)-1) if event[i]==1 and (event[i+1]==0 or event[i-1]==0)]
[2, 5, 8, 11]
我们在列表的开头和/或结尾添加并添加列表,以确保找到ones
我们预先结束并附加列表,以确保在列表的开始和/或结束处找到
事件的角位。事件是否如下所示:[0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1]
?@jamylak yes,它是一个整数列表事件看起来如下:[0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,1,1,1,1]
。@jamylak是的,这是一个整数列表,但我刚刚意识到@lazyr是最好的解决方案,因为在一个列表中,我们失去了单个1的序列。这是我的错,虽然我做到了,但我刚刚意识到@lazyr是最好的解决方案,因为在单个列表中,我们丢失了单个1的序列。谢谢,但问题不是最好的,我做了编辑。谢谢,但问题不是最好的,我做了编辑。