列表是否有类似“ strip”的方法?

Cha*_* Ye 4 python list-comprehension list strip

strippython中的buildin 方法可以轻松剥离满足自定义条件的填充子字符串。例如

"000011110001111000".strip("0")
Run Code Online (Sandbox Code Playgroud)

将修剪字符串两侧的填充零,然后返回11110001111

我想为列表找到类似的功能。例如,对于给定的列表

input = ["0", "0", "1", "1", "0", "0", "1", "0", "1", "0", "0", "0"]
Run Code Online (Sandbox Code Playgroud)

预期的输出将是

output = ["1", "1", "0", "0", "1", "0", "1"]
Run Code Online (Sandbox Code Playgroud)

示例input中的项目过于简化,它们可能是任何其他python对象

list comprehension 将删除所有项目,而不是填充项目。

[i for i in input if i != "0"]
Run Code Online (Sandbox Code Playgroud)

gmd*_*mds 5

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
Run Code Online (Sandbox Code Playgroud)

输出:

['1', '1', '0', '0', '1', '0', '1']
Run Code Online (Sandbox Code Playgroud)