首页 > 解决方案 > 我有一个包含 1 和 0 的列表序列,我希望以这种格式输出,其中创建子列表直到满足零

问题描述

这是输入,输出应如图所示。这是我尝试过的:

input a = [1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0]
output a = [[1,1,0],[1,1,1,0],[1,0],[1,1,0]]
def new_list(x):
    new = []
    for item in range(length(x)):
        if  x[item]== 0:
            new.append(x[:item+1])
    return new

标签: python

解决方案


首先提取到0元素的内部。然后用它对原始列表进行切片:

a = [1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0]
def new_list(x):
    indices = [i for i,e in enumerate(x) if e == 0] # indices of zeros
    indices = [0] + [i+1 for i in indices] # 0 is 1st slice, +1 is for slicing (1 higher than index)
    ii1,ii2 = indices[:-1],indices[1:] # first and second index for each sub-list
    return [x[i1:i2] for i1,i2 in zip(ii1,ii2)]
print(new_list(a))

推荐阅读