You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现列表的列表中空行与空列的移除(非Pandas方案)

列表的列表处理实现方案

第一步:剔除全为空元素的子列表

直接用列表推导式筛选掉所有元素都是None的子列表:

# 过滤掉所有元素都是None的子列表
filtered_lol = [sublist for sublist in lol if not all(x is None for x in sublist)]

拿示例输入来说,里面的[None, None, None]会被直接去掉,得到[["a", None, "c"], ["g", None, "i"], ["j", None, None]]。

第二步:移除所有子列表中该索引均为空的列

先找出那些在所有过滤后的子列表里,对应位置全是None的索引,然后只保留剩下的索引对应的元素:

# 找出需要保留的索引:排除所有子列表该位置都是None的索引
keep_indices = [idx for idx in range(len(filtered_lol[0])) if not all(sublist[idx] is None for sublist in filtered_lol)]
# 提取每个子列表中符合要求的元素
result = [[sublist[idx] for idx in keep_indices] for sublist in filtered_lol]

示例里过滤后的子列表中,索引1的元素全是None,所以这个索引会被排除,最终得到目标结果[["a", "c"], ["g", "i"], ["j", None]]。

完整代码示例

可以把两步拆分成更易读的版本:

# 示例输入
lol = [["a", None, "c"], [None, None, None], ["g", None, "i"], ["j", None, None]]

# 分步实现
filtered = [sublist for sublist in lol if not all(x is None for x in sublist)]
keep_indices = [i for i in range(len(filtered[0])) if not all(s[i] is None for s in filtered)]
final_result = [[s[i] for i in keep_indices] for s in filtered]

print(final_result)  # 输出: [['a', 'c'], ['g', 'i'], ['j', None]]

内容的提问来源于stack exchange,提问作者Moses Bakst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 03:30:48