與this question類似,但不是用一個項目替換另一個項目,而是用一個列表的內容替換任何一個項目的出現。用另一個列表的內容替換列表項目
orig = [ 'a', 'b', 'c', 'd', 'c' ]
repl = [ 'x', 'y', 'z' ]
desired = [ 'a', 'b', 'x', 'y', 'z', 'd', 'x', 'y', 'z' ]
# these are all incorrect, or fail to compile
[ repl if x == 'c' else x for x in orig ]
[ [a for a in orig] if x == 'c' else x for x in orig ]
[ (a for a in orig) if x == 'c' else x for x in orig ]
[ a for a in orig if x == 'c' else x for x in orig ]
編輯:清楚我的意思是,以取代所有出現的項目,而不僅僅是第一。 (道歉的人誰沒有涵蓋他們的答案的話。)
優勢!我應該在我的問題中明確指出,我需要更換所有實例,而不僅僅是第一個實例。 – moswald 2013-02-19 17:05:51
@DSM - 這是標準拼合成語嗎?一路上我錯過了一個 - 也許是因爲我仍然很難解析它:)。 'itertools.chain'對我來說... – mgilson 2013-02-19 17:08:55
@mgilson:好的,這是標準的* listcomp * flattening成語。 :^) – DSM 2013-02-19 17:10:19