[英]How to convert this line of code from Python to Julia?
In brief, I have the code below in Python简而言之,我在 Python 中有以下代码
[n, m] = f()
and I want to convert it to Julia, which will not be more than one line (I hope).我想将它转换为 Julia,不会超过一行(我希望)。
Here is an example in Python:这是 Python 中的示例:
from numpy import *
x = [0,1,2]
y = [3,4,5]
x = array(x)
y = array(y)
def f():
z = concatenate((x, y))
a = z*2
b = z*3
return [a, b]
def g():
[n,m] = f()
n = n/2
m = m/3
return [n, m]
print(g())
This is how I wanted it to be in Julia, but did not work:这就是我希望它在 Julia 中的样子,但没有用:
x = [0,1,2]
y = [3,4,5]
function f()
z = vcat(x, y)
a = z*2
b = z*3
return [a, b]
end
function g()
[n, m] = f()
n = n/2
m = m/3
return [n, m]
end
print(g())
Here is how I made it work, but I do not want codes like this:这是我如何让它工作的,但我不想要这样的代码:
x = [0,1,2]
y = [3,4,5]
function f()
z = vcat(x, y)
a = z*2
b = z*3
global c = [a, b]
return c
end
function g()
n = c[1]
m = c[2]
n = n/2
m = m/3
return [n, m]
end
f()
print(g())
Thank you very much.非常感谢你。
Just drop square brackets like this:像这样放下方括号:
x = [0,1,2]
y = [3,4,5]
function f()
z = vcat(x, y)
a = z*2
b = z*3
return a, b # here it is not needed, but typically in such cases it is dropped to return a tuple
end
function g()
n, m = f() # here it is needed
n = n/2
m = m/3
return n, m # here it is not needed, but typically in such cases it is dropped to return a tuple
end
print(g())
The reason why it is typically better to return a Tuple
rather than a vector is that Tuple
does not perform auto promotion of values (+ it is non-allocating):返回Tuple
而不是向量通常更好的原因是Tuple
不执行值的自动提升(+它是非分配的):
julia> (1, 2.0) # here 1 stays an integer
(1, 2.0)
julia> [1, 2.0] # here 1 got implicitly converted to 1.0
2-element Vector{Float64}:
1.0
2.0
Of course if you want such implicit behavior use a vector.当然,如果您想要这种隐式行为,请使用向量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.