python - 用另一个列表的内容替换列表项

标签 python list-comprehension

类似于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 ]

编辑:明确表示我要替换该项目的所有 次出现,而不仅仅是第一个。 (向没有在回答中涵盖该案例的任何人道歉。)

最佳答案

>>> 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']

当然,如果您不知道 'c' 在索引 2 处,您可以使用 orig.index('c') 找出该信息。

关于python - 用另一个列表的内容替换列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14962931/

相关文章:

python - 增加 Django Session 的时间

python - 一个用于复制来自文件的行的衬里 (Python)

python - 如何使用 ast.NodeTransformer 将 List Comprehensions 转换为 For Loops?

python - 在 Python 中,是否有一种简洁的方法来使用具有多个迭代器的列表理解?

python - 按列表列表中的索引对项目进行操作

python - 如果嵌套在函数中,listcomp 无法访问 exec 调用的代码中定义的局部变量

python - 如何在Python中将数组中的整数转换为 float ?

python - 迭代列表并将该值用作字典键

Python:Telnet 密码未使用 pexpect 通过脚本获取

Python Celery 线程、工作线程和 vCPU