Netlogo adding to list of lists

2019-08-10 00:02发布

问题:

I am looking to add patch variable values to a list of empty lists. The patches are divided into different zones, and I'm trying to see how certain patch variables differ by zone. I have an empty list of lists (actually contains 12 lists, but for simplicity):

set mylist [[] [] [] []]

And a list corresponding to the different zones:

set zone-list [1 2 3 4]

Here's how I'm trying to build the lists:

(foreach mylist zone-list [set ?1 lput (sum-zone-variable ?2) ?1])

to-report sum-zone-variable [ n ]
  report (sum [patch-variable] of patches with [zone = n])
end

When I run this, mylist stays empty (ie unchanged). I think the problem is with the foreach statement, but I can't figure out what it is. Any help?

回答1:

I can see the thinking behind foreach mylist [ set ?1 ... ], but NetLogo doesn't work that way. set ?1 ... has no effect on the original list. NetLogo lists are immutable, and ?1 is not a reference to an updatable location in a list — it's just a temporary variable into which a value has been copied. So set ?1 ... is something you will basically never write.

If I understand your question correctly, the relevant primitive here is map. This should do the job:

set mylist (map [lput (sum-zone-variable ?2) ?1] mylist zonelist)


回答2:

Your basic approach is ok except that you must assign to a name. E.g.,

globals [mylist zone-list n-zones]

patches-own [zone zone-variable]

to setup
  set n-zones 4
  set zone-list n-values n-zones [?]
  ask patches [set zone one-of zone-list]
  set mylist n-values n-zones [[]]
end

to go
  ask patches [set zone-variable random-float 1]
  foreach zone-list [
    let total sum [zone-variable] of patches with [zone = ?]
    let oldvals item ? mylist
    set mylist replace-item ? mylist (lput total oldvals)
  ]
end

However, you might want to use the table extension for this.