Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any `strip`-liked method for a list?

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"]
like image 925
Chang Ye Avatar asked Mar 28 '19 06:03

Chang Ye


People also ask

Does strip work on lists?

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.

How do you strip all elements in a list Python?

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.

How do you strip an array in Python?

Removing Array Elements You can use the pop() method to remove an element from the array.


2 Answers

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']
like image 151
gmds Avatar answered Oct 02 '22 12:10

gmds


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.

like image 26
gilch Avatar answered Oct 02 '22 12:10

gilch