简体   繁体   中英

How to return instead of print

I get the desired result from using print() but I want the same result when using a return . How can I change this to a return ? When I do it only returns the first key, value where I want to have the four that are in the BST.

 def inOrder(self, aNode):
       if aNode:
        self.inOrder (aNode.leftChild)
        print (aNode.key + ' ' + aNode.payload +'\n')
        self.inOrder (aNode.rightChild)

The result I am looking for is to have four keys followed by their value.

To do exactly what you want, you need to use the yield keyword (details for the yield from statement here )

 def inOrder(self, aNode):
       if aNode:
        yield from self.inOrder(aNode.leftChild)
        yield (aNode.key, aNode.payload)
        yield from self.inOrder(aNode.rightChild)

Which will return a generator, you can "expand" it by using list(inOrder(...))

You could also have a dedicated argument that you would update as you go through:

 def inOrder(self, aNode, res=[]):
       if aNode:
        self.inOrder(aNode.leftChild, res)
        res.append((aNode.key, aNode.payload))
        self.inOrder(aNode.rightChild, res)

Which will provide similar results.

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