Remove leading and trailing zeros from a multidimensional list in Python

I have a list, for example:

my_list = [[1,2,2,1], [0,0,1,2], [1,2,0,0], [1,0,0,1]] 

I need to remove only internal and trailing zeros from internal lists, so that in the end I:

 new_list = [[1,2,2,1], [1,2], [1,2], [1,0,0,1]] 

Any help is greatly appreciated.

+4
source share
5 answers
 for sub_list in my_list: for dx in (0, -1): while sub_list and sub_list[dx] == 0: sub_list.pop(dx) 
+11
source
 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.

You can also simply:

 >>> 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 it’s best not to convert to np.array unless you intend to use this type later.

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

can 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]] 
+4
source

Using a single list comprehension, sliced ​​using generator filtering:

 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] 
+2
source

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]] 
0
source

All Articles