从Python的多维列表中删除前导和尾随零 [英] Remove leading and trailing zeros from multidimensional list in Python
本文介绍了从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)
这篇关于从Python的多维列表中删除前导和尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文