我一直在使用这篇文章(how to do replacing-item in use nested list)作为指导,了解如何替换列表中符合给定条件的项目。
具体来说,我想用值= 0.5替换列表中的所有零。但是,我提出的代码似乎只是替换了列表中的第一个零,我似乎无法找出原因。
这是我的代码:
to-report A-new-list-without-zeros [old new the-list]
let A-index-list n-values length the-list [?]
( foreach A-index-list the-list
[ if ?2 = old
[ report replace-item ?1 the-list new ]
])
report the-list
end
这就是发生的事情:
observer> show A-new-list-without-zeros 0 0.5 [0 1 0 5 5 0]
observer: [0.5 1 0 5 5 0]
任何帮助将不胜感激!感谢
答案 0 :(得分:3)
map
比foreach
更容易完成此任务。
NetLogo 6语法:
to-report A-new-list-without-zeros [old new the-list]
report map [[x] -> ifelse-value (x = old) [new] [x]] the-list
end
NetLogo 5语法:
to-report A-new-list-without-zeros [old new the-list]
report map [ifelse-value (? = old) [new] [?]] the-list
end
答案 1 :(得分:2)
只要您使用report
,它就会退出该过程并报告该点的输出。使用代码的快速修复是更改if语句中的report
行,以便它替换当前索引处的项目:
to-report A-new-list-without-zeros [old new the-list]
let A-index-list n-values length the-list [?]
( foreach A-index-list the-list
[ if ?2 = old
[ set the-list replace-item ? the-list new ]
])
report the-list
end
observer> print A-new-list-without-zeros 0 0.5 [ 0 1 0 5 5 0 ]
[0.5 1 0.5 5 5 0.5]