mos*_*ald 2 python list-comprehension
与此问题类似,但我不想用一个项目替换另一个项目,而是想用列表的内容替换任何一个项目.
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 ]
Run Code Online (Sandbox Code Playgroud)
编辑:说清楚我打算替换所有出现的项目,而不仅仅是第一次.(向在答案中未涉及该案件的任何人道歉.)
>>> orig = [ 'a', 'b', 'c', 'd' ]
>>> repl = [ 'x', 'y', 'z' ]
>>> desired = list(orig) #can skip this and just use `orig` if you don't mind modifying it (and it is a list already)
>>> desired[2:3] = repl
>>> desired
['a', 'b', 'x', 'y', 'z', 'd']
Run Code Online (Sandbox Code Playgroud)
当然,如果你不知道它'c'在索引2,你可以orig.index('c')用来找出那些信息.
| 归档时间: |
|
| 查看次数: |
4857 次 |
| 最近记录: |