从 Netlogo 中的属性值查找列表中的第一项

问题描述 投票:0回答:1

我正在 Netlogo 中使用一个模型,其中每个代理都有一条通过网络的路径。每个节点都有一个名为“mode”的属性,其值为

["bike" "bus" "train" "u-g"]
。我想找到第一个与前一个模式不同的 myway 项目。例如:

observer> ask turtle 4455 [show myway]
 
turtle 4455 > [(vertex 77445) (vertex 66227) (vertex 39816) (vertex 98972) (vertex 47091) (vertex 88001)]

与模式的对应关系是

["bike" "bike" "bike" "bike" "train" "train"]
,所以我需要找到第4项,即列表中的第一个不同模式。

我尝试解决这个问题是创建一个新列表,其中每个顶点的模式如下:

ask turtle 4455 [
let mymodes [] 
foreach myway [ r -> 
set mymodes lput [mode] of r mymodes]
show mymodes]

[ "bike" "bike" "bike" "bike" "train" "train"]

我现在尝试使用命令位置和第一个来查找列表中第一列“火车”的位置:

show position (first mymodes != "Bici") mymodes

但它返回“false”,我需要这个位置。

感谢您的帮助!

list find position netlogo
1个回答
0
投票

这是一种方法 - 迭代列表中项目的位置/索引,并使用它们来比较

item i
item i-1
。在这里,我设置了一个名为
report-first-different
的报告器,如果找到第一个不同项目,则返回第一个不同项目的位置;如果没有发现差异,则返回 -1(例如,如果仅存在“自行车”):

extensions [rnd]

to-report report-first-different [input-list]
  ; Iterate over the indices of the input-list 
  foreach range length input-list [ i ->
    ; Ignore the first item
    if i > 0 [
      ; If there is a difference between the item from current index
      ; and the item from previous index, report the current index
      if item i input-list != item (i - 1) input-list [ report i]     
    ]
  ]  
  ; If all items are the same, report -1
  report -1 
end


to show-example
  ; Set up a test list, biased towards 'bike'
  let ls [ ["bike" 5 ] ["bus" 1]  ["train" 1] ]
  let test-list map first map [ y -> rnd:weighted-one-of-list ls [ x -> last x ] ] range 8
   
  print "Test list:"
  print test-list
  
  print "Position of first different:"
  print report-first-different test-list
end

输出示例:

Test list:
[bike bike bus bus bike bus train bike]
Position of first different:
2

Test list:
[bike bike bike bike bike bus bike train]
Position of first different:
5

Test list:
[bike bike bike bike bike bike bike bike]
Position of first different:
-1
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.