如何删除空白的2D列表行?

时间:2014-06-02 11:17:00

标签: python list python-2.7

我正在尝试从python中的2D列表中删除空白元素/行。

[['a', 'b', 'c', 'd'], 
 [], [], [], [], [], [], 
 ['a', 'b', 'c', 'd'], 
 ['a', 'b', 'c', 'd']]

抱歉,如果这很简单,但我从来没有在matlab中遇到过这个问题而且我很难过!

2 个答案:

答案 0 :(得分:4)

带有None

filter()会为您删除空值:

lst = filter(None, lst)

或者,您可以使用列表推导来获得相同的结果:

lst = [nested for nested in lst if nested]

演示:

>>> lst = [['a', 'b', 'c', 'd'], [], [], [], [], [], [], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]
>>> filter(None, lst)
[['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]
>>> [nested for nested in lst if nested]
[['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]

答案 1 :(得分:-2)

假设外部列表名为list,那么您可以删除内部空列表,如下所示:

list = [['61710480', '385950.51', '6526136.92', '59.369\n'], 
      [], [], [], [], [], [], 
      ['61710487', '381808.8', '6519876.8', '53.292\n'], 
      ['61710488', '381808.8', '6519876.8', '53.183\n']]

list = [l for l in list if len(l)>0]