当前位置: 首页 > 后端技术 > Python

Python代码阅读(第三十五篇):彻底(深入)展开嵌套列表

时间:2023-03-25 19:46:01 Python

Python代码阅读合集介绍:为什么不推荐Python初学者直接看项目源码本文阅读的代码实现了一个嵌套列表的所有功能list嵌套的层次结构被完全展开以形成一个简单的函数列表。本文阅读的代码片段来自30-seconds-of-python。deep_flattenfromcollections.abcimportIterabledefdeep_flatten(lst):返回[aforiinlstforaindeep_flatten(i)]ifisinstance(lst,Iterable)else[lst]#EXAMPLESdeep_flatten([1,[2],[[3],4],5])#[1,2,3,4,5]deep_flatten函数接收嵌套列表并返回完全展开的列表。该函数将isinstance()与collections.abc.Iterable结合使用来检查元素是否可迭代(列表与否)。如果是,则递归调用列表理解内的deep_flatten()函数,否则返回[lst]。原函数:defdeep_flatten(lst):return[aforiinlstforaindeep_flatten(i)]ifisinstance(lst,Iterable)else[lst]可以重写为:defdeep_flatten(lst):ifisinstance(lst,Iterable):return[aforiinlstforaindeep_flatten(i)]else:return[lst]函数判断lst是否为可迭代对象,执行return[aforiinlstforaindeep_flatten(i)].此时如果i是一个可迭代对象,会在dee??p_flatten(i)中继续调用listcomprehension,继续展开嵌套list;如果i不是可迭代对象,【deep_flatten(i)中会返回i】,此时a的值为i,在列表推导中会得到一个不可迭代对象的元素,嵌套元素上的层将被解开。更进一步,该函数可以重写为:fromcollections.abcimportIterabledefdeep_flatten(lst):temp=[]deff(lst):ifisinstance(lst,Iterable):foriinlst:forainf(i):temp.append(a)return[]else:return[lst]f(lst)returntempprint(deep_flatten([1,[2],[[3],4],5]))#[1,2,3,4,5]