nested-lists - 更改嵌套列表中的过滤值

标签 nested-lists netlogo

我有一个嵌套列表,其中每个子列表的结构如下:[[xcor ycor]weight]。 每个刻度我都想更新这些子列表样本中的权重。

我使用 Rnd 扩展(以及非常 helpful answers/comments )从嵌套列表 total 生成样本(例如大小为 2):

set total [ [[0 1] 1] [[2 3] 2] [[4 5] 3] [[6 7] 4] [[0 1] 1] ]
set sample rnd:weighted-n-of 2 total [ last ? ]

然后我更新样本中的权重(假设将它们乘以 2)并将它们映射到各自的 [xcor ycor] 对。

let newWeights (map [last ? * 2] sample)
let updatedSample (map list (map [first ?] sample) newWeights)

如何替换 total 中的这些条目,同时记住它可能包含重复的条目?

这似乎是 replace-item 的完美工作,但我不知道如何构建适当的索引,然后从 updatedSample 传递相应的值。

最佳答案

这是一个很大的问题。您正在使用的数据结构称为 association list ,或简称 alist,其中键为 [xcor ycor],值为权重。鉴于您的任务,最好使用键而不是索引来查找内容。因此,replace-item 在这里并没有真正的帮助。相反,我们可以在 total 上运行 map,使用 updatedSample 中的值(如果存在),并默认为 中的值总计。首先,我们需要一个方便的函数来在列表中查找内容。在 lisp(一种影响 NetLogo 的语言)中,这称为 assoc。这是:

to-report assoc [ key alist ]
  foreach alist [ if key = (first ?) [ report ? ] ]
  report false
end

请注意,如果 alist 不包含 key ,则返回 false。如果该函数返回的条目不为 false,我们希望使用该条目,否则使用其他内容。因此,我们需要另一个辅助函数:

to-report value-or-else [ value default ]
  report ifelse-value (value = false) [ default ] [ value ]
end

最后,我们可以编写一个执行映射的函数:

to-report update-alist [ alist updated-entries ]
  report map [ value-or-else (assoc first ? updated-entries) ? ] alist
end

这是实际操作:

observer> show update-alist [[[0 1] 1] [[2 3] 2] [[4 5] 3] [[6 7] 4] [[0 1] 1]] [[[0 1] 10] [[4 5] 45]]
observer: [[[0 1] 10] [[2 3] 2] [[4 5] 45] [[6 7] 4] [[0 1] 10]]

您可能希望将其命名为update-alisttotalupdatedSample

关于nested-lists - 更改嵌套列表中的过滤值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22790871/

相关文章:

netlogo:比较品种的属性?

counter - Netlogo,如何显示刻度数

python - 修改嵌套列表

html - 如何使 3 列嵌套列表只有内部装订线(没有外部边距)?

python-2.7 - PYTHON 2.7 - 修改列表列表并重新组装而不改变

Netlogo:计算图形/网络的直径

collision-detection - 乌龟碰了怎么杀?

NetLogo - 寻找具有最大值的补丁

java - 尝试遍历 HashMap 时收到 ConcurrentModificationException

c# - 搜索 List<List<string>> 的最佳方法是什么?