python - 我有一个包含 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
解决方案
首先提取到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))
推荐阅读
- python - 对符合条件的行的列子集进行排序
- android - 使用相同的按钮暂停 Android 倒计时
- python - 导入的模块应该如何访问全局常量(VERBOSE=True)等?
- jenkins - Jenkins 的工作可以观察一个 repo 的变化,以触发另一个 repo 的构建吗?
- c# - 从该对象中的脚本激活和停用该对象上的脚本(初学者的麻烦)
- python - 未找到 Python Linux Google drive API 客户端安装模块
- javascript - angular-cli 编译错误 + monorepo:错误 TS2451:无法重新声明块范围变量“ngDevMode”
- php - 在 if($_POST) 块内初始化的 PHP 数组不能在它之外使用
- dart - 没有 AppBar 的 Flutter 应用设计
- r - R:geom_point() 使用函数来选择形状?