how to do replacing-item in use nested list

2020-05-07 19:29发布

replacing in nested list ??

for example

[[1 2][3 4] [5 1]]

to

[[99 2][3 4] [5 1]]

Can anybody please clarify the use of lists in Netlogo?

标签: netlogo
1条回答
够拽才男人
2楼-- · 2020-05-07 19:59

Your question is somewhat underspecified. How do you want to decide which item gets changed?

I'll suppose that you want to do it by indices, e.g. "0th item of 0th sublist". Then that's:

to-report replace-subitem [index1 index2 lists value]
  let old-sublist item index1 lists
  report replace-item index1 lists (replace-item index2 old-sublist value)
end

observer> show replace-subitem 0 0 [[1 2] [3 4] [5 1]] 99
observer: [[99 2] [3 4] [5 1]]

You could also imagine doing the replacement according to other criteria. For example, suppose we want to change all of the occurrences of 1 in the first item of a sublist to 99. Then that's:

to-report replace-first [old new the-list]
  if first the-list = old
    [ report replace-item 0 the-list new ]
  report the-list
end

to-report replace-firsts [old new lists]
  report map [replace-first old new ?] lists
end

observer> show replace-firsts 1 99 [[1 2] [3 4] [1 1]]
observer: [[99 2] [3 4] [99 1]]

A lot of other answers are possible as well, depending on exactly what problem you're trying to solve.

查看更多
登录 后发表回答