Python:使用当前缩进级别的知识进行打印
Python: printing with knowledge of current level of indentation
假设我有下一个列表:
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 循环遍历列表时,我只需要一种方法来了解当前级别。
def indent(thing, current_indentation=""):
print current_indentation + str(thing)
try:
for item in thing:
indent(item, " " * 4 + current_indentation)
except TypeError: # thing is not iterable
pass
xl = [[[0,0], [-1,1], [-2,2]], [[-3,3], [-4, 4], [-5,5]]]
indent(xl)
输出:
[[[0, 0], [-1, 1], [-2, 2]], [[-3, 3], [-4, 4], [-5, 5]]]
[[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
5
关键是当你想编写代码来处理任意嵌套循环时你需要递归。
我用'isinstance'函数判断输入的日期类型是否为列表
def print_by_hierarchy(data,indentation):
if isinstance(data,list):
space = 2*indentation
for sub_data in data:
print(' '*space + str(sub_data))
print_by_hierarchy(sub_data,indentation +1)
else:
return
test_data = [[[0,0], [-1,1], [-2,2]], [[-3,3], [-4, 4], [-5,5]]]
print_by_hierarchy(test_data,0)
output:
[[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
5
假设我有下一个列表:
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 循环遍历列表时,我只需要一种方法来了解当前级别。
def indent(thing, current_indentation=""):
print current_indentation + str(thing)
try:
for item in thing:
indent(item, " " * 4 + current_indentation)
except TypeError: # thing is not iterable
pass
xl = [[[0,0], [-1,1], [-2,2]], [[-3,3], [-4, 4], [-5,5]]]
indent(xl)
输出:
[[[0, 0], [-1, 1], [-2, 2]], [[-3, 3], [-4, 4], [-5, 5]]]
[[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
5
关键是当你想编写代码来处理任意嵌套循环时你需要递归。
我用'isinstance'函数判断输入的日期类型是否为列表
def print_by_hierarchy(data,indentation):
if isinstance(data,list):
space = 2*indentation
for sub_data in data:
print(' '*space + str(sub_data))
print_by_hierarchy(sub_data,indentation +1)
else:
return
test_data = [[[0,0], [-1,1], [-2,2]], [[-3,3], [-4, 4], [-5,5]]]
print_by_hierarchy(test_data,0)
output:
[[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
5