如何将这行代码从 Python 转换为 Julia?

How to convert this line of code from Python to Julia?

简而言之,我在 Python

中有以下代码
[n, m] = f()

我想把它转换成 Julia,不会超过一行(我希望)。

下面是 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())

这就是我希望它在 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())

这是我如何让它工作的,但我不想要这样的代码:

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())

非常感谢。

像这样放下方括号:

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())

通常 return Tuple 而不是矢量的原因是 Tuple 不执行值的自动提升(+ 它是 non-allocating):

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

当然,如果您想要这种隐式行为,请使用向量。