2015-09-26 40 views
-1
的当前水平的知识打印

比方说,我有一张表:的Python:缩进

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实体)。我只是需要一种方法来知道当前级别,当我遍历循环列表。

+0

你说的是'enumerate'? https://docs.python.org/2/library/functions.html#enumerate –

+0

在你的复杂情况下,你是在谈论一个lxml元素? –

+0

如果你真正的情况是打印一个lxml元素,那么你可能不需要手动编码这个,你应该尝试类似于''print(etree.tostring(root,pretty_print = True))''。 –

回答

1
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 

的一点是,当你想要编写代码来处理任意嵌套的循环,你需要递归。

+0

感谢您的想法。 –

1

我用“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