python - 列表是否有任何“strip”喜欢的方法?
问题描述
python 中的 buildinstrip
方法可以轻松剥离满足自定义条件的填充子字符串。例如
"000011110001111000".strip("0")
将修剪字符串两侧的填充零,并返回11110001111
.
我想为列表找到类似的功能。例如,对于给定的列表
input = ["0", "0", "1", "1", "0", "0", "1", "0", "1", "0", "0", "0"]
预期输出将是
output = ["1", "1", "0", "0", "1", "0", "1"]
示例input
中的项目过于简化,它们可能是任何其他 python 对象。
list comprehension
将删除所有项目,而不是填充项目。
[i for i in input if i != "0"]
解决方案
itertools.dropwhile
从两端使用:
from itertools import dropwhile
input_data = ["0", "0", "1", "1", "0", "0", "1", "0", "1", "0", "0", "0"]
def predicate(x):
return x == '0'
result = list(dropwhile(predicate, list(dropwhile(predicate, input_data))[::-1]))[::-1]
result
输出:
['1', '1', '0', '0', '1', '0', '1']
推荐阅读
- python - python - 无法让音频播放器工作
- python - 如何为基于类的视图继承 DRF 的权限?
- nusmv - 为 NuSMV 中的变量分配随机值
- aws-lambda - 除 Launch 请求外,其他任何意图请求均无响应
- bash - 如果早期部分失败,我可以阻止管道的后续部分运行吗?
- linux - 多级单父单子进程树?
- asp.net-mvc - 安装适用于 Visual Studio 2017 的 Oracle 开发人员工具时出错
- vue.js - 如何在 Vue.js 中绑定动画持续时间?
- javascript - jest.mock 中的 Jest 'TypeError: is not a function'
- c++ - AT 命令响应解析器