Python:使用当前缩进级别的知识打印

2024-10-01 02:34:40 发布

您现在位置: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实体)。我只需要一种方法来知道当前的水平,当我迭代列表与for周期。你知道吗


Tags: infor层次结构方式情况手动pythonic级别
2条回答

我使用'isinstance'函数来确定输入日期类型是否为list

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
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

关键是,当您想编写代码来处理任意嵌套的循环时,您需要递归。你知道吗

相关问题 更多 >