我有一个像
这样的功能import random
import multiprocessing
def list_append(count, id, out_queue):
a = [random.random() for i in range(count)]
out_queue.put((id, a))
if __name__ == "__main__":
size = 10000 # Number of random numbers to add
procs = 2 # Number of processes to create
jobs = []
q = multiprocessing.Queue()
for i in range(0, procs):
process = multiprocessing.Process(target=list_append,
args=(size, i, q))
process.start()
jobs.append(process)
result += [q.get() for _ in range(procs)]
for j in jobs:
j.join()
print("List processing complete.")
如果我然后用
调用它dbh2vol <- function(dbh,hgt,...){
if (missing(hgt)){
hgt = 2
cat("hgt is missing. Set to 2")
}
vol = dbh * hgt
return(vol)
}
一切都很好。如果我有像这样的东西
Vol = dbh2vol(dbh=10,hgt=4)
#40
正如所料。但如果那时我做了
Vol = dbh2vol(dbh=10,param=4)
#hgt is missing. Set to 2[1] 20
Vol = dbh2vol(dbh=10,h=4)
#40
被解释为h=4
。为什么以及如何避免这种行为,即参数如何与其名称完全匹配?
答案 0 :(得分:2)
你观察到的是命名函数参数的部分匹配,据我所知你不能禁用它。请参阅r语言定义以获取更多信息https://cran.r-project.org/doc/manuals/R-lang.html#Argument-matching
也许您可以将hgt参数放入三个点并检查一下?当然你放松了位置匹配。
dbh2vol <- function(dbh, ...){
hgt <- list(...)$hgt
if (is.null(hgt)) {
hgt <- sqrt(dbh)
cat("hgt has been calculated with some_other_function")
}
vol = dbh * hgt
return(vol)
}
答案 1 :(得分:1)
您可以尝试这样做,而不是将dbh和hgt作为参数传递:
pars <- list(
dbh = 10,
h = 5
)
dbh2vol <- function(pars){
with(pars,{
if (!exists("hgt")){
hgt <- 2
cat("hgt is missing. Set to 2")
}
vol <- dbh * hgt
return(vol)
})
}
dbh2vol(pars)
## hgt is missing. Set to 2[1] 20
这使您可以轻松地将参数传递给其他函数。