了解Python中的嵌套列表
作者:互联网
我在理解什么是一级列表,二级列表和三级列表时有些麻烦.我只想看一下它,就知道它是一个,但是我对括号感到困惑.
什么定义了列表中的级别?
这被视为三级列表吗?
[ [[5,6],7], 9]
还是这是一个三级列表?
[ [7,2], [[2,3],4], [[[5,6],7],9] ]
解决方法:
嵌套列表的概念并不是很复杂,它只是意味着您可以在列表中包含一个列表.在该列表中,您可能还有另一个列表,依此类推.
术语一级,二级或n级列表未得到广泛使用,使用术语嵌套级更为常见.因此,让我们编写一个小的算法来可视化嵌套级别:
>>> def nestprint(lst, level=0):
... print('{} is at nesting level {}'.format(lst, level))
... for item in lst:
... if isinstance(item, list):
... nestprint(item, level+1)
对于给定的列表,这将打印出每个列表的嵌套级别.这是您的示例所做的:
>>> nestprint([[[5,6],7],9])
[[[5, 6], 7], 9] is at nesting level 0
[[5, 6], 7] is at nesting level 1
[5, 6] is at nesting level 2
>>>
>>> nestprint([[7,2],[[2,3],4],[[[5,6],7],9]])
[[7, 2], [[2, 3], 4], [[[5, 6], 7], 9]] is at nesting level 0
[7, 2] is at nesting level 1
[[2, 3], 4] is at nesting level 1
[2, 3] is at nesting level 2
[[[5, 6], 7], 9] is at nesting level 1
[[5, 6], 7] is at nesting level 2
[5, 6] is at nesting level 3
希望这可以为您清除一切.
标签:nested-lists,list,arrays,python 来源: https://codeday.me/bug/20191027/1943765.html