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)