簡體   English   中英

如何在 python 的同一行上使用 for 循環打印?

[英]How to printing using for loop on same line in python?

我正在嘗試為我的一個程序制作一個類似於視覺文件的文件。 child_dataparent_data

我正在嘗試使 output 類似於:

parent_data
----------|child_data
           child_data
           child_data
--------------------|grandchild_data
                     grandchild_data
----------|child_data
parent_data

我的第一次嘗試是這樣的:

def visual(self, ID):
     for i in range(self.generation(ID)): # finding how many parents of the ID 
         print(----|, end='')             # there are

但這不起作用,它在同一行打印,但當我打電話給沒有父母的 ID 時,它也一直返回 NONE。 所以 output 將是: None parent_data

您要使用的模式是讓節點跟蹤其子節點,然后使用遞歸 function 進行打印。

它的基本思想是這樣的:

class Node():
    def __init__(self, name, children=[]):
        self.children = children
        self.name = name

    def print(self, level=0):
        print('\t'*level, self.name)
        level += 1
        for child in self.children:    
            child.print(level)

a = Node('parent', [ Node('child', [ Node('grandchild') ]) ])

a.print()

但是要獲得您想要的確切 output ,您需要執行以下操作:

class Node():
    def __init__(self, name, children=[]):
        if not isinstance(children, list):
            children = [children]

        self.children = children
        self.name = name

    def print(self, level=0, special_print=False):
        ''' Recursively print out all of the children in a nice visual way.
        level keeps track of the indentation as we go along.
        special_print prefixes the outputted line with a bunch of --- followed by a |
        This special printing happens whenever there is a change in indentation '''

        if level is 0:
            print(self.name)
        elif special_print:
            print('----------'*level + '|' + self.name)
        else:
            print('          '*level + ' ' + self.name)

        level += 1
        special_print = True
        for child in self.children:
            child.print(level, special_print)
            special_print = bool(child.children)

a = Node('parent_data', [
        Node('child_data'),
        Node('child_data'),
        Node('child_data', [
            Node('grandchild'),
            Node('grandchild')
        ]),
        Node('child_data'),
    ])

a.print()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM