简体   繁体   中英

How to determine the number of layers of lists a list has?

Given that a list can be within a list, and list can be within a list within a list, and so forth, I'd like to know the number of lists that exist within another list within a list.

For example,

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

I'd like to know that l1 is 1 list deep, l2 is 2 lists deep, l3 is 3 lists deep and so forth.

Assuming it's a simple structure of nested lists like your examples, you can simply count the number opening brackets :)

l4 = [[[[1]]]]
print len(str(l4)) - len(str(l4).replace('[', '')) # 4

I hope this helps,

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

print depth(l1)

You have to dig into every sublist.

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

Using len(numpy.array(list)) could work

print(len(numpy.array(l2)))  # return 2
print(len(numpy.array(l3)))  # return 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM