python-分解多列表嵌套

2023-01-31 02:01:01 python

针对多列表嵌套,如何获取所有元素?

之前使用for循环+if判断,进行分解,如下:

    for first_layer in lists:
        if isinstance(first_layer,list):
            for second_layer in first_layer:

                if isinstance(second_layer,list):

                    for third_layer in second_layer:

                        print third_layer

        else:
            print first_layer

但是,若遇到列表有4重嵌套、5重嵌套...等等,代码显得无比复杂、臃肿。


于是想到函数复用性,如下:

#!/usr/bin/env python
#coding:utf-8
fruit=['a','b',123,['c',345,'d',['e','f',90],22,'cc'],'po',34]
def layer(lists):
    for first_layer in lists:
        if isinstance(first_layer,list):
            layer(first_layer)
        else:
            print first_layer
layer(fruit)

这样,不管多少个列表嵌套,只需传参给函数就行,可以实现逐级分解。函数还能被移植调用,可用性增强。

相关文章