简体   繁体   English

如何在递归循环中继续附加到 numpy 数组,然后打印出最终结果/将其传递给另一个 function?

[英]How to keep appending to a numpy array inside a recurive loop and then print out the final result/pass it to another function?

In recursion, how to use a numpy array to keep appending your values in it, and once the recursion is done, to return/pass it to the main function or outside the current function to print it out or use it for another function?在递归中,如何使用 numpy 数组在其中继续附加您的值,并在递归完成后将其返回/传递给主 function 或在当前 function 之外打印出来或将其用于另一个 function?

I've tried a lot of ways but none work, it would be great if someone could help me.我尝试了很多方法,但都没有用,如果有人能帮助我,那就太好了。 I usually end up with a blank list for every recursion or the numpy array just gets written over and when i return it to the other function, it shows 0. This is a basic python question,, pls help.我通常每次递归都会得到一个空白列表,或者 numpy 数组刚刚被覆盖,当我将它返回给另一个 function 时,它显示 0。这是一个基本的 python 问题,请帮助。 It would help if you could write the basic syntax with an example of updating an array within a recursion and printing out JUST the final updated array.如果您可以使用在递归中更新数组并打印出最终更新的数组的示例来编写基本语法,那将会有所帮助。

I do not know for sure what is causing a problem, but a common mistake is that you initialize the variable within the function call which makes a new local variable for every function call (even in recursion) and it does not know about the state of that variable in the "parent function" that called it.我不确定是什么导致了问题,但一个常见的错误是您在 function 调用中初始化变量,这为每个 function 调用(即使在递归中)创建一个新的局部变量并且它不知道 state调用它的“父函数”中的那个变量。

You can do one of two things:您可以执行以下两项操作之一:

  1. Create a global numpy array instead of a local one made on the stack for a specific call to a function.创建一个全局 numpy 数组,而不是在堆栈上为对 function 的特定调用创建的本地数组。
  2. Pass the numpy array to as an input to consequent function calls in the recursion loop将 numpy 数组作为输入传递给递归循环中的后续 function 调用

It depends on your use case or preference.这取决于您的用例或偏好。 The first one is pretty obvious.第一个很明显。 As for the second one, you could do something like:至于第二个,你可以这样做:

function(arg1, arg2, ..., np_array=None, depth=0):

  if depth == 0:
    np_array = # Initialization of the array
  
  # Function stuff ...
  
  # For the recursive call
  depth += 1
  function(arg1, arg2, ..., np_array=np_array, depth=depth)
  
  if depth == 0: # Or at whatever depth you want to print the array  
  print(np_array) # After recursion ends

As a piece of advice: you can always avoid recursion by using some sort of data structure (like a stack) and a loop.作为一条建议:您始终可以通过使用某种数据结构(如堆栈)和循环来避免递归。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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