python使用递归函数输出嵌套列表中的每个元素

a 夏天 提交于 2019-11-29 18:28:41
A = [1, 2, ["a", "b", [11, 22, 33, ("@", "$"), [111, 222, {"k1": "k1"}, {1001, 1002, 1003}]], "c"], 5, 6]

def GetAll(li):
    for item in li:
        if isinstance(item, (tuple, list, dict, set)) == True:
            GetAll(item)
        else:
            print(item)


GetAll(A)

 

​A = [1, 2, ["a", "b", [11, 22, 33, ("@", "$"), [111, 222, {"k1": "k1"}, {1001, 1002, 1003}]], "c"], 5, 6]

def getitem(l, level=0):
    for item in l:
        if isinstance(item, (tuple, list, dict, set)):
            getitem(item, level + 1)
        else:
            for tab in range(level):
                print('\t', end='')
            print(item)


getitem(A)  #根据嵌套关系,显示缩进

​

isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。

 

isinstance() 与 type() 区别:

  • type() 不会认为子类是一种父类类型,不考虑继承关系。

  • isinstance() 会认为子类是一种父类类型,考虑继承关系。

如果要判断两个

类型是否相同推荐使用 isinstance()。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!