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

2024-10-01 02:22:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 对象方法函数字符串in示例列表for
3条回答

你可以用while/pop直接脱衣。你知道吗

input = ["0", "0", "1", "1", "0", "0", "1", "0", "1", "0", "0", "0"]
while input and input[-1] == "0": input.pop()

你可以用itertools.dropwhile留下strip,但是你可能需要建立一个新的列表。你知道吗

from itertools import dropwhile
input = [*dropwhile(lambda x: x=='0', input)]

或者,您可以通过转换为deque从两端高效地执行while/pop。你知道吗

from collections import deque
input = ["0", "0", "1", "1", "0", "0", "1", "0", "1", "0", "0", "0"]
input = deque(input)
while input and input[-1] == '0': input.pop()
while input and input[0] == '0': input.popleft()

(而且input()已经是一个内置函数,所以最好不要对变量重复使用这个名称。)

从两端使用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']

没有list方法,但实现这样一个函数并不难:扫描所需的索引,然后切片到它们。你知道吗

def strip_seq(predicate, xs):
    def scan(xs):
        return next((i for i, x in enumerate(xs) if not predicate(x)), 0)
    return xs[scan(xs) : -scan(reversed(xs)) or None]

xs = ["0", "0", "a", "1", "0", "0", "1", "0", "b", "0", "0", "0"]
print(strip_seq(lambda x: x=='0', xs))  # ['a', '1', '0', '0', '1', '0', 'b']

这应该适用于任何可切片的序列类型,包括字符串和元组。你知道吗

相关问题 更多 >