Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove leading and trailing zeros from multidimensional list in Python [closed]

Tags:

python

numpy

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_list = [[1,2,2,1], [1,2], [1,2], [1,0,0,1]]

Any help much appreciated.

like image 391
Darwin Tech Avatar asked Nov 29 '12 20:11

Darwin Tech


1 Answers

for sub_list in my_list:
    for dx in (0, -1):
        while sub_list and sub_list[dx] == 0:
            sub_list.pop(dx)
like image 143
Steven Rumbalski Avatar answered Nov 09 '22 15:11

Steven Rumbalski