簡而言之,我在 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())
非常感謝。
uj5u.com熱心網友回復:
只需像這樣洗掉方括號:
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())
Tuple回傳 a而不是向量通常更好的原因是它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
當然,如果您想要這種隱式行為,請使用向量。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430300.html
