如何确定列表具有的列表层数? [英] 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.
例如,
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个列表,依此类推.
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
这篇关于如何确定列表具有的列表层数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文