如何替换列表中满足给定条件的所有项目
How to replace all items meeting a given criteria in a list
我一直在使用这个 post (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]
如有任何帮助,我们将不胜感激!谢谢
任何时候您使用 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]
使用 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
我一直在使用这个 post (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]
如有任何帮助,我们将不胜感激!谢谢
任何时候您使用 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]
使用 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