首页 > 解决方案 > 列表是否有任何“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"]

标签: pythonlistlist-comprehensionstrip

解决方案


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']

推荐阅读