我正在尝试从 python 中的二维列表中删除空白元素/行。
[['a', 'b', 'c', 'd'],
[], [], [], [], [], [],
['a', 'b', 'c', 'd'],
['a', 'b', 'c', 'd']]
抱歉,如果这很简单,但我在 matlab 中从未遇到过这个问题,而且很困惑!
最佳答案
filter()
使用 None
将为您删除空值:
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']]
关于python - 如何删除空白的二维列表行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23993244/