您可以只使用切片:
>>> a = [ 1, 'replace_this', 4 ]
>>> a[1:2] = [2, 3]
>>> a
[1, 2, 3, 4]
正如 @mgilson 指出的那样 - 如果您不知道要替换的元素的位置,那么您可以使用a.index
找到它......(见他的评论)
与不使用切片相关的更新
Using itertools.chain
,确保replacements
有可迭代对象:
from itertools import chain
replacements = {
'replace_this': [2, 3],
4: [7, 8, 9]
}
a = [ 1, 'replace_this', 4 ]
print list(chain.from_iterable(replacements.get(el, [el]) for el in a))
# [1, 2, 3, 7, 8, 9]