Netlogo:按元素对等长列表求和

Netlogo: Sum a list of lists of equal length element-wise

我有一个等长列表列表,例如

[[0 1 0] [2 3 0] [4 4 2] [0 1 0]]

我怎样才能得到列表[6 9 2],它按条目顺序总结了四个列表中的条目?

更擅长列表的人会出现并更干净地做这件事,但这行得通。

to testme
  let inlist [[0 1 0] [2 3 0] [4 4 2] [0 1 0]]
  let outlist []
  let ii 0
  while [ii < length item 1 inlist ]
  [ let items map [ x -> item ii x ] inlist
    print items
    set outlist lput reduce [ [a b] -> a + b] items outlist
    set ii ii + 1
  ]
  print outlist
end

它的作用是创建第一个条目的列表(使用 let items),然后将它们与 reduce 相加,然后移动到第二个条目等

您可能还想看看这个问题 Netlogo: How to compute sum of items of lists within a list?,它适用于个人条目。

一直在找"one-liner",终于做出来了:

to-report aggregate-lists [list-of-lists]
   report map [ i -> sum (map [li -> item i li] list-of-lists) ] range length item 0 list-of-lists
end

您将一个报告器映射到一个报告器,该报告器将所有列表的 item i 求和到索引向量 range length item 0 list-of-lists(在示例中为 [0 1 2])。

let _lst [[0 1 0] [2 3 0] [4 4 2] [0 1 0]] show reduce [[?1 ?2] -> (map + ?1 ?2)] _lst

作为程序:

to-report aggregate-lists [list-of-lists]
  report reduce [[?1 ?2] -> (map + ?1 ?2)] list-of-lists
end