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"]
你可以用while/pop直接脱衣。你知道吗
你可以用
itertools.dropwhile
留下strip,但是你可能需要建立一个新的列表。你知道吗或者,您可以通过转换为deque从两端高效地执行while/pop。你知道吗
(而且
input()
已经是一个内置函数,所以最好不要对变量重复使用这个名称。)从两端使用
itertools.dropwhile
:输出:
没有list方法,但实现这样一个函数并不难:扫描所需的索引,然后切片到它们。你知道吗
这应该适用于任何可切片的序列类型,包括字符串和元组。你知道吗
相关问题 更多 >
编程相关推荐