Python展平字典值内任意嵌套列表为一维列表的方法
嵌套列表值字典展平方案
问题场景
- 数据存储结构为
defaultdict(list),字典每个键对应的值为列表类型,但存在多层子列表嵌套的情况。 - 需求为忽略所有列表嵌套层级,将每个键对应的值统一处理为仅包含字符串元素的一维扁平列表。
示例输入
from collections import defaultdict sample_dict1 = defaultdict(list, {'File1.xlsx': ['Path/NEW/Subpath/File1.xlsx'], 'File2.xlsx': ['Path/NEW/Subpath/File2.xlsx'], 'File3.xlsx': ['Path/NEW/Subpath/File3.xlsx', ['Path/OLD/Subpath/File3.xlsx']], 'File4.xlsx': ['Path/NEW/Subpath/File4.xlsx', ['Path/OLD/Subpath/File4.xlsx'], ['Path/changed/Subpath/File4.xlsx']] } )
期望输出
output = defaultdict(list, {'File1.xlsx': ['Path/NEW/Subpath/File1.xlsx'], 'File2.xlsx': ['Path/NEW/Subpath/File2.xlsx'], 'File3.xlsx': ['Path/NEW/Subpath/File3.xlsx', 'Path/OLD/Subpath/File3.xlsx'], 'File4.xlsx': ['Path/NEW/Subpath/File4.xlsx', 'Path/OLD/Subpath/File4.xlsx', 'Path/changed/Subpath/File4.xlsx'] } )
原有代码错误点
编写的递归展平代码存在3个问题:
- 语法错误:调用
flatten时写了多余的右方括号flatten(k]),不符合Python语法规则。 - 传参逻辑错误:
flatten需要传入待展平的列表值,代码传入的是字典的键k(即文件名字符串),完全没有处理对应的值v。 - 依赖缺失:代码中使用了
Iterable类型判断,但没有提前导入该类型,运行会触发NameError。
修正后代码
from collections import defaultdict from collections.abc import Iterable def flatten(xs): for x in xs: # 字符串是最终要保留的元素,直接返回 if isinstance(x, str): yield x # 其余可迭代对象(嵌套列表)继续递归展平 elif isinstance(x, Iterable): yield from flatten(x) # 遍历字典,对每个键对应的值做展平处理 for k, v in sample_dict1.items(): sample_dict1[k] = list(flatten(v))
运行以上代码后,sample_dict1的结构就和期望输出完全一致,支持任意深度的列表嵌套展平。
内容的提问来源于stack exchange,提问作者matt.aurelio
相关产品推荐
相关产品推荐

