python索引区间_python如何判断连续满足条件的区间?

list = [

1,

0,

1,

1,

1,

1,

1,

0,

1,

1,

1,

0,

0,

0,

1,

1,

1,

1,

1,

1,

1,

0,

0,

0,

1,

1,

0,

1,

1,

0,

1,

]

out = []

temp = []

index = 0

list_length = len(list)

# 本质上是对数据分组,

# 创建一个名为temp的空list, 然后遍历数据list, 当前数据和前一个数据有一个不是0的时候向 temp 中添加当前数据,

# 当前数据和下一个数据都是 0 的时候, temp作为一个数据分组, 添加到最后的输出list中. 然后temp重新设置为空list

# 主要是注意 数据list的第一个数据和最后一个数据

while True:

# 数据list的第一个数据

if index == 0:

if list[index] == 0 and list[index + 1] == 0:

temp = []

else:

temp.append(list[index])

# 数据list 的最后一个数据

elif index == list_length - 1:

if list[index - 1] != 0 or list[index] != 0:

temp.append(list[index])

if temp:

out.append(temp)

print(

"当前temp_list: {}, 索引: {}, 数据list长度: {}, 当前数据: {}".format(

temp, index, list_length, list[index]

)

)

break

# 其他数据

else:

if list[index] == 0 and list[index + 1] == 0:

if temp:

out.append(temp)

temp = []

else:

if list[index - 1] != 0 or list[index] != 0:

temp.append(list[index])

print(

"当前temp_list: {}, 索引: {}, 数据list长度: {}, 当前数据: {}".format(

temp, index, list_length, list[index]

)

)

index += 1

print("最后输出分组:")

print(out)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值