2017-05-24 75 views
2

我一直在使用此帖子(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] 

任何幫助,將不勝感激!謝謝

回答

1

無論何時使用report,它都會退出該過程並在該點報告輸出。使用您的代碼速戰速決是改變report線在你的if語句,以便它目前的指數在替換項:

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] 
+0

非常感謝@Luke!C這很好用!只是好奇,爲什麼嵌套'report'命令在我用作指導的帖子中起作用?是因爲這個例子只關注第一個項目還是因爲它處理了嵌套列表? – skivvy

+0

不用擔心!如果你在談論@Seth Tisue在你的鏈接中的第二部分,你會注意到他在記者的內部嵌套了一名記者。所以在那種情況下,他的「先報告」要麼用替換**或**來報告列表而不替換第一項 - 但它不會繼續。一旦調用了「報告」,該過程就完成了。訣竅是'replace-first'嵌套在'replace-firsts'中,所以'replace-firsts'正在迭代傘狀列表並使用'replace-first'來評估子列表。那有意義嗎? –

+0

啊,我明白了......現在我明白了。感謝您解釋並幫助我再次出現! :) – skivvy

2

這個任務更容易與mapforeach完成。

的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 
+0

哦,是啊!我不認爲我曾經使用'ifelse-value',但這很好。謝謝@SethTisue! – skivvy

相關問題