The buildin strip
method in python can strip padding substring that meet a custom condition easily. eg
"000011110001111000".strip("0")
will trim the padding zero on both side of the string, and return 11110001111
.
I would like to find a similar function for a list. eg, for a given list
input = ["0", "0", "1", "1", "0", "0", "1", "0", "1", "0", "0", "0"]
the expect output will be
output = ["1", "1", "0", "0", "1", "0", "1"]
The items in the example input
are over simplified, they might be any other python objects.
list comprehension
will remove all the items, instead of the padding ones.
[i for i in input if i != "0"]
The Python String strip() function works only on strings and will return an error if used on any other data type like list, tuple, etc.
The remove() method is one of the ways you can remove elements from a list in Python. The remove() method removes an item from a list by its value and not by its index number.
Removing Array Elements You can use the pop() method to remove an element from the array.
Use itertools.dropwhile
from both ends:
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
Output:
['1', '1', '0', '0', '1', '0', '1']
No list method, but it's not hard to implement such a function: Scan for the desired indexes and then slice to them.
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']
This should work on any of the sliceable sequence types, including strings and tuples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With