简体   繁体   中英

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

I am trying to make a file like visual for one of my programs. There's child_data and parent_data

And i'm trying to make the output similar to:

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

My first try I used some like this:

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

But that didn't work, it was printing on the same line but also kept returning NONE when I called to an ID with no parent. So the output would be: None parent_data

The pattern you are going to want to use is to have nodes that keep track of their children, and then use a recursive function to do the printing.

The basic idea of it is this:

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

But to get the exact output in you were wanting, you would need to do something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM