Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何确定列表的层数?_Python_List - Fatal编程技术网

Python 如何确定列表的层数?

Python 如何确定列表的层数?,python,list,Python,List,假设列表可以在列表中,列表可以在列表中的列表中,等等,我想知道列表中另一个列表中存在的列表的数量 比如说, l1 = [1] #1 is within 1 list l2 = [[1]] #1 is within 2 lists l3 = [[[1]]] #1 is within 3 lists l4 = [[[[1]]]] #1 is within 4 list 我想知道l1是1个列表深度,l2是2个列表深度,l3是3个列表深度,以此类推。您必须深入挖掘每个子列表 def depth(ls

假设列表可以在列表中,列表可以在列表中的列表中,等等,我想知道列表中另一个列表中存在的列表的数量

比如说,

l1 = [1] #1 is within 1 list
l2 = [[1]] #1 is within 2 lists 
l3 = [[[1]]] #1 is within 3 lists
l4 = [[[[1]]]] #1 is within 4 list

我想知道l1是1个列表深度,l2是2个列表深度,l3是3个列表深度,以此类推。

您必须深入挖掘每个子列表

def depth(lst):
    if not isinstance(lst, list):
        return 0
    else:
        return 1 + max(depth(sublist) for sublist in lst)

你必须深入研究每一个子列表

def depth(lst):
    if not isinstance(lst, list):
        return 0
    else:
        return 1 + max(depth(sublist) for sublist in lst)

假设它是一个简单的嵌套列表结构,就像您的示例一样,您可以简单地计算打开方括号的数量:)


假设它是一个简单的嵌套列表结构,就像您的示例一样,您可以简单地计算打开方括号的数量:)

我希望这有帮助

def depth (givenList):
  for i in givenList:
    if not isinstance(i,list):
        return 1
    else:
        return depth(i)+1

print depth(l1)
我希望这有帮助

def depth (givenList):
  for i in givenList:
    if not isinstance(i,list):
        return 1
    else:
        return depth(i)+1

print depth(l1)
c=lambda x:(1+c(x[0])如果类型(x)是list else 0
那么
c(l4)
c=lambda x:(1+c(x[0])如果类型(x)是list else 0
那么
c(l4)