Python:函数可以返回数组和变量吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19507501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Can a function return an array and a variable?
提问by dcnicholls
Is there a simple way to get a function to return a np.array and a variable?
有没有一种简单的方法可以让函数返回一个 np.array 和一个变量?
eg:
例如:
my_array = np.zeros(3)
my_variable = 0.
def my_function():
my_array = np.array([1.,2.,3.])
my_variable = 99.
return my_array,my_variable
my_function()
so that the values calculated in the function can be used later in the code? The above ignores the values calculated in the function.
以便稍后可以在代码中使用函数中计算的值?以上忽略了函数中计算的值。
I tried returning a tuple {my_array, my_variable} but got the unhashable type message for np.array
我尝试返回一个元组 {my_array, my_variable} 但得到了 np.array 的 unhashable 类型消息
DN
DN
采纳答案by Andy
It's not ignoring the values returned, you aren't assigning them to variables.
它没有忽略返回的值,您没有将它们分配给变量。
my_array, my_variable = my_function()
回答by Curry
easy answer
简单的答案
my_array, my_variable = my_function()
回答by Jonathon Reinhart
Your function is correct. When you write return my_array,my_variable
, your function is actually returning a tuple (my_array, my_variable)
.
你的功能是正确的。当您编写时return my_array,my_variable
,您的函数实际上是在返回一个元组(my_array, my_variable)
。
You can first assign the return value of my_function()
to a variable, which would be this tuple I describe:
您可以首先将返回值分配my_function()
给一个变量,这将是我描述的这个元组:
result = my_function()
Next, since you know how many items are in the tuple ahead of time, you can unpack the tupleinto two distinct values:
接下来,由于您提前知道元组中有多少项,您可以将元组解包为两个不同的值:
result_array, result_variable = result
Or you can do it in one line:
或者您可以在一行中完成:
result_array, result_variable = my_function()
Other notes related to returning tuples, and tuple unpacking:
与返回元组和元组解包相关的其他注意事项:
I sometimes keep the two steps separate, if my function can return None
in a non-exceptional failure or empty case:
如果我的函数可以None
在非异常失败或空情况下返回,我有时会将这两个步骤分开:
result = my_function()
if result == None:
print 'No results'
return
a,b = result
# ...
Instead of unpacking, alternatively you can access specified items from the tuple, using their index:
您可以使用它们的索引从元组中访问指定的项目,而不是解包:
result = my_function()
result_array = result[0]
result_variable = result[1]
If for whatever reason you have a 1-item tuple:
如果由于某种原因您有一个 1 项元组:
return (my_variable,)
You can unpack it with the same (slightly awkward) one-comma syntax:
您可以使用相同的(有点笨拙的)单逗号语法解压缩它:
my_variable, = my_function()
回答by Ciro Xue
After the definition of my_function, use my_function = np.vectorize(my_function).
For example,
在定义 my_function 之后,使用 my_function = np.vectorize(my_function)。
例如,
def jinc(x):
if x == 0.0:
return 1
return 2*j1(x)/x
jinc = np.vectorize(jinc)