在Python中,用生成器的递归的方式展开一个嵌套的list。
def flatten(nested):
try:
for sublist in nested:
if isinstance(sublist,str):
yield sublist
else:
for element in flatten(sublist):
yield element
except TypeError:
yield nested运行后结果:
>>> list(flatten([[[1],2],[3,[4,'abc']]]))
[1, 2, 3, 4, 'abc']
本文介绍了一种使用Python生成器递归方式来展开任意层级的嵌套列表的方法,并通过一个具体示例展示了如何将嵌套的数字和字符串列表转换为扁平化的列表。
2188

被折叠的 条评论
为什么被折叠?



