从Python的多维列表中删除前导和尾随零
问题描述:
我有一个列表,例如:
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]]
非常感谢您的帮助.
答
for sub_list in my_list:
for dx in (0, -1):
while sub_list and sub_list[dx] == 0:
sub_list.pop(dx)