与此问题类似,但不是用另一个项目替换一个项目,而是我想用列表的内容替换任何一个项目的出现。
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 ]
编辑:明确表示我的意思是替换所有出现的项目,而不仅仅是第一个。(向没有在回答中涵盖该案例的任何人道歉。)