按 Netlogo 中的元素对列表进行分组
Grouping lists by elements in Netlogo
假设我在 Netlogo 中有一个模型,现在我有兴趣开发一个 reporter/procedure 根据列表的第一个元素对列表进行分组。
举个例子,假设
globals[list1 list2 list3 listoflists
ordered-list-a
ordered-list-b
]
to setup
set list1 ["a" "b" "c"]
set list2 ["a" "c" "d"]
set list3 ["b" "a" "c"]
set listoflists (list list1 list2 list3)
end
我想创建一个列表列表,以便在每个列表中都有以相同元素开头的列表。因此,所需的输出是
[[["a" "b" "c"]["a" "c" "d"]]["b" "a" "c"]]]
即,第一个元素聚合所有以 a 开头的列表,第二个元素聚合所有以 "b" 开头的列表。
理想情况下,这应该可以扩展到大量。我试过了
to create-list
set ordered-list-a []
set ordered-list-b []
(foreach listoflists [[i] ->
if item 0 i = "a" [set ordered-list-a lput i ordered-list-a]
if item 0 i = "b" [set ordered-list-b lput i ordered-list-b]
])
end
然后从 a 和 b 创建一个列表,这可以解决问题,但是 a) 它非常混乱,b) 要求我事先知道列表的长度,而在实际情况下我不知道 (这是一个海龟程序)和 c) 似乎有很多不必要的编码。
有没有什么方法可以将上述过程扩展到任意数量的起始元素(也许在 while 循环内?)并且不需要为每个初始列表元素创建一个列表?
非常感谢
我假设所需的输出应该是:[[["a" "b" "c"]["a" "c" "d"]][["b" "a" "c"]]]
。我相信你在第二组之前错过了 [
。
无论如何,一个简单但有点低效的方法是:
; items is a list of items to be grouped
; key is an anonymous reporter that extracts the group label from a single item
to-report group-by [ items key ]
let keys remove-duplicates map key items
report map [ k -> filter [ x -> (runresult key x) = k ] items ] keys
end
注意上面是一个完全广义的分组函数。要在你的情况下使用它,你会这样做:
group-by listoflists [ l -> first l ]
一种更有效的方法是使用 table:group-items reporter from the table extension.
table:group-items listoflists [ l -> first l ]
假设我在 Netlogo 中有一个模型,现在我有兴趣开发一个 reporter/procedure 根据列表的第一个元素对列表进行分组。 举个例子,假设
globals[list1 list2 list3 listoflists
ordered-list-a
ordered-list-b
]
to setup
set list1 ["a" "b" "c"]
set list2 ["a" "c" "d"]
set list3 ["b" "a" "c"]
set listoflists (list list1 list2 list3)
end
我想创建一个列表列表,以便在每个列表中都有以相同元素开头的列表。因此,所需的输出是
[[["a" "b" "c"]["a" "c" "d"]]["b" "a" "c"]]]
即,第一个元素聚合所有以 a 开头的列表,第二个元素聚合所有以 "b" 开头的列表。
理想情况下,这应该可以扩展到大量。我试过了
to create-list
set ordered-list-a []
set ordered-list-b []
(foreach listoflists [[i] ->
if item 0 i = "a" [set ordered-list-a lput i ordered-list-a]
if item 0 i = "b" [set ordered-list-b lput i ordered-list-b]
])
end
然后从 a 和 b 创建一个列表,这可以解决问题,但是 a) 它非常混乱,b) 要求我事先知道列表的长度,而在实际情况下我不知道 (这是一个海龟程序)和 c) 似乎有很多不必要的编码。
有没有什么方法可以将上述过程扩展到任意数量的起始元素(也许在 while 循环内?)并且不需要为每个初始列表元素创建一个列表?
非常感谢
我假设所需的输出应该是:[[["a" "b" "c"]["a" "c" "d"]][["b" "a" "c"]]]
。我相信你在第二组之前错过了 [
。
无论如何,一个简单但有点低效的方法是:
; items is a list of items to be grouped
; key is an anonymous reporter that extracts the group label from a single item
to-report group-by [ items key ]
let keys remove-duplicates map key items
report map [ k -> filter [ x -> (runresult key x) = k ] items ] keys
end
注意上面是一个完全广义的分组函数。要在你的情况下使用它,你会这样做:
group-by listoflists [ l -> first l ]
一种更有效的方法是使用 table:group-items reporter from the table extension.
table:group-items listoflists [ l -> first l ]