假设我有下一个清单:
xl = [[[0,0], [-1,1], [-2,2]], [[-3,3], [-4, 4], [-5,5]]
我要打印它并保存层次结构:
for el in xl:
print el
for iel in el:
print ' '*4 + str(iel)
for iiel in iel:
print ' '*8 + str(iiel)
>>>
[[0, 0], [-1, 1], [-2, 2]]
[0, 0]
0
0
[-1, 1]
-1
1
[-2, 2]
-2
2
[[-3, 3], [-4, 4], [-5, 5]]
[-3, 3]
-3
3
[-4, 4]
-4
4
[-5, 5]
-5
层次结构可以有任何深度
我需要一些pythonic的方式来打印,以保持当前的迭代级别(不手动管理缩进)。你知道吗
更进一步说,我的实际情况更复杂(迭代lxml实体)。我只需要一种方法来知道当前的水平,当我迭代列表与for周期。你知道吗
我使用'isinstance'函数来确定输入日期类型是否为list
输出:
关键是,当您想编写代码来处理任意嵌套的循环时,您需要递归。你知道吗
相关问题 更多 >
编程相关推荐