python - 如何删除空白的二维列表行?

标签 python list python-2.7

我正在尝试从 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/

相关文章:

list - List 的应用实例在使用 QuickCheck/Checkers 的组合律测试中永远运行

python - 如何将字符串列表转换为整数列表 - 很多事情似乎不起作用

python - 根据 value_counts() 更改 pandas 数据框中的值

python - 将字符串中的负数转换为 float (Python)?

python - 从谷歌搜索中提取结果数

python - 导入错误 : DLL load failed: The specified module could not be found in python

python - 如何在 python 中从 orderedDict 中删除条目

vb.net - 使用列表而不是数组来创建类中的对象

python - 在给定范围内查找列表的所有可能子列表的高效和 Pythonic 方法,以及将其中的所有元素相乘后的最小乘积?

python-2.7 - 如何设置 setuptools 存档文件名?