更新时间:2022-12-07 18:49:47
还有更好的方法吗?
is there a better way?
是的.
NetLogo 6.0随附了 rnd
扩展. (对于早期版本的NetLogo,您也可以单独下载扩展名 )
NetLogo 6.0 comes with the rnd
extension bundled. (You can also download the extension separately for earlier versions of NetLogo.)
rnd
扩展名提供了 rnd:weighted-one-of-list
原语,它确实可以完成您要执行的操作:
The rnd
extension offers the rnd:weighted-one-of-list
primitive, which does exactly what you're trying to do:
extensions [ rnd ]
to-report pick
let probabilities [0.1 0.2 0.4 0.3]
let some_list ["String1" "String2" "String3" "String4"]
report first rnd:weighted-one-of-list (map list some_list probabilities) last
end
让我稍微整理一下最后一个表达式:
Let me unpack the last expression a bit:
(map list some_list probabilities)
的作用是将两个列表压缩"在一起,以获取以下形式的对列表:[["String1" 0.1] ["String2" 0.2] ["String3" 0.4] ["String4" 0.3]]
.
The role of (map list some_list probabilities)
is to "zip" the two lists together, in order to get a list of pairs of the form: [["String1" 0.1] ["String2" 0.2] ["String3" 0.4] ["String4" 0.3]]
.
该对列表作为第一个参数传递给rnd:weighted-one-of-list
.我们将last
作为rnd:weighted-one-of-list
的第二个参数传递,以告知它应使用每对中的第二个作为概率.
That list of pairs is passed as the first argument to rnd:weighted-one-of-list
. We pass last
as the second argument of rnd:weighted-one-of-list
to tell it that it should use the second item of each pair as the probability.
rnd:weighted-one-of-list
随机选择一对对,然后返回整个对.但是,由于我们只对这对中的第一项感兴趣,因此我们使用first
提取它.
rnd:weighted-one-of-list
then picks one of the pairs at random, and returns that whole pair. But since we're only interested in the first item of the pair, we use first
to extract it.
要了解该代码的工作原理,有助于了解匿名过程工作.请注意,我们如何利用简洁的语法将list
传递给map
以及将last
传递给rnd:weighted-one-of-list
.
To understand how that code works, it helps to understand how Anonymous procedures work. Note how we make use of the concise syntax for passing list
to map
and for passing last
to rnd:weighted-one-of-list
.