Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使我的方法返回列表而不是字符串?_Python - Fatal编程技术网

Python 如何使我的方法返回列表而不是字符串?

Python 如何使我的方法返回列表而不是字符串?,python,Python,所以我有一个预排序方法,它只需在终端上打印出一串数字,例如: def preorder(self): if self.root != None: self._preorder(self.root) def _preorder(self, cur_node): lyst = [] if cur_node != None: lyst.append(str(cur_node.data))

所以我有一个预排序方法,它只需在终端上打印出一串数字,例如:

    def preorder(self):
        if self.root != None:
            self._preorder(self.root)

    def _preorder(self, cur_node):
        lyst = []
        if cur_node != None:
            lyst.append(str(cur_node.data))
        #print(str(cur_node.data))
            lyst += self._preorder(cur_node.left_child)
            lyst += self._preorder(cur_node.right_child)
        return lyst

然而,我希望它是一个列表,而不是。因此,我创建了一个空列表,尝试将其追加,并将其扩展到递归调用。然而,这仍然没有回报。我到底遗漏了什么?

您的
\u preorder
函数返回一个列表,但您的
preorder
函数对它没有任何作用

277
291
295
385
317
309
301
306
313
314
362
351
328
321
325
323
343
335
334
342
346
344
345
347
361
355
357
378
377
390
399
您可以将此更改为:

def preorder(self):
    if self.root != None:
        self._preorder(self.root)  # nothing is done with this value
    # end of function -- no return so we return None

现在,
preorder
的调用者将得到一个列表作为返回值。由于
\u preorder
通过返回一个空列表来处理
None
的情况,似乎
preorder
应该无条件地调用它。

您需要从
preorder
返回一些内容
def preorder(self):
    return self._preorder(self.root)