2015-09-26 78 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