Skip to content Skip to sidebar Skip to footer

Remove Leading And Trailing Zeros From Multidimensional List In Python

I have a list such as: my_list = [[1,2,2,1], [0,0,1,2], [1,2,0,0], [1,0,0,1]] I need to remove only the leading and trailing zeros from the inner lists, so that I end up with: new

Solution 1:

for sub_list in my_list:
    for dx in (0, -1):
        while sub_list and sub_list[dx] == 0:
            sub_list.pop(dx)

Solution 2:

my_list = [[1,2,2,1], [0,0,1,2], [1,2,0,0], [1,0,0,1]]
my_list =[np.trim_zeros(np.array(a)) for a in my_list]
>>> my_list
[array([1, 2, 2, 1]), array([1, 2]), array([1, 2]), array([1, 0, 0, 1])]

If you want numpy.

Can also just do:

>>> my_list =[np.trim_zeros(a) for a in my_list]
>>> my_list
[[1, 2, 2, 1], [1, 2], [1, 2], [1, 0, 0, 1]]

Some timings:

Numpy
>>> timeit.timeit('my_list =[np.trim_zeros(a) for a in my_list]',setup='import numpy as np; my_list = [[1,2,2,1], [0,0,1,2], [1,2,0,0], [1,0,0,1]]', number=10000)
0.08429217338562012

Numpy w/convert array
>>> timeit.timeit('my_list =[np.trim_zeros(np.array(a)) for a in my_list]',setup='import numpy as np; my_list = [[1,2,2,1], [0,0,1,2], [1,2,0,0], [1,0,0,1]]', number=10000)
0.6929900646209717

So really best off not to convert at np.array unless you are going to use that type later.


Solution 3:

new_list = [map(int,"".join(map(str,x)).strip("0")) for x in my_list]

might work

>>> new_list = [map(int,"".join(map(str,x)).strip("0")) for x in my_list]
>>> new_list
[[1, 2, 2, 1], [1, 2], [1, 2], [1, 0, 0, 1]]

Solution 4:

Using a single list comprehension, with slicing by filtered generator comprehension:

new_list = [l[next((i for i, n in enumerate(l) if n != 0), 0):
              next((len(l) - i for i, n in enumerate(reversed(l)) if n != 0), 0)]
            for l in my_list]

Solution 5:

using regex and itertools.chain():

In [91]: my_lis=[[1,2,2,1], [0,0,1,2], [1,2,0,0], [1,0,0,10]]

In [92]: my_lis1=[[y.split() for y in filter(None,re.split(r"\b\s?0\s?\b",
                                     " ".join(map(str,x))))] for x in my_lis]

In [93]: [map(int,chain(*x)) for x in my_lis1]
Out[93]: [[1, 2, 2, 1], [1, 2], [1, 2], [1, 10]]

Post a Comment for "Remove Leading And Trailing Zeros From Multidimensional List In Python"