且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将数字列表的值与netlogo中名称列表中的项匹配?

更新时间:2021-08-23 00:52:35

Jen的解决方案很好,但是我认为这对于

Jen's solution is perfectly fine, but I think this could also be a good use case for the table extension. Here is an example:

extensions [table]

to demo

  let usedstrategies ["chicken" "duck" "monkey" "dog"]
  let zq [5 6 7 8]  
  let strategies table:from-list (map list zq usedstrategies)  

  ; get item corresponding with number 7:
  print table:get strategies 7

end

这里的表"是一种数据结构,其中一组键与值相关联.在这里,数字是关键,策略是价值.

A "table", here, is a data structure where a set of keys are associated with values. Here, your numbers are the keys and the strategies are the values.

如果您尝试获取表中没有键的项目(例如table:get strategies 9),则会出现以下错误:

If you try to get an item for which there is no key in the table (e.g., table:get strategies 9), you'll get the following error:

扩展例外:表中没有9的值.

Extension exception: No value for 9 in table.

这里有一些有关代码工作原理的详细信息.

Here is a bit more detail about how the code works.

要构建表,我们使用table:from-list报告程序,该报告程序将列表列表作为输入,并返回给您一个表,其中每个子列表的第一项用作键,第二项用作键.值.

To construct the table, we use the table:from-list reporter, which takes a list of lists as input and gives you back a table where the first item of each sublist is used as a key and the second item is used as a value.

要构建列表列表,请使用 map 一个>原始的.这部分要理解起来有些棘手. map原语需要两种输入:一个或多个列表,以及要应用于这些列表元素的报告器.报告者排在第一位,整个表达式需要放在括号内:

To construct our list of lists, we use the map primitive. This part is a bit more tricky to understand. The map primitive needs two kind of inputs: one or more lists, and a reporter to be applied to elements of these lists. The reporter comes first, and the whole expression needs to be inside parentheses:

(map list zq usedstrategies)

此表达式将两个列表压缩"在一起:它使用zq的第一个元素和usedstrategies的第一个元素,并将它们传递到

This expression "zips" our two lists together: it takes the first element of zq and the first element of usedstrategies, passes them to the list reporter, which constructs a list with these two elements, and adds that result to a new list. It then takes the second element of zq and the second element of usedstrategies and does the same thing with them, until we have a list that looks like:

[[5 "chicken"] [6 "duck"] [7 "monkey"] [8 "dog"]]

请注意,也可以将zip表达式写成:

Note that the zipping expression could also have be written:

(map [ [a b] -> list a b ] zq usedstrategies)

...但是这是一种更round回的方式. list报告程序本身已经是我们想要的.无需构造一个单独的匿名报告程序来完成相同的任务.

...but it's a more roundabout way to do it. The list reporter by itself is already what we want; there is no need to construct a separate anonymous reporter that does the same thing.