用python中的列表替换元素

Igo*_*bin 3 python list

在python中,用另一个列表中的元素替换列表中的元素的最佳方法是什么?

例如,我有:

a = [ 1, 'replace_this', 4 ]
Run Code Online (Sandbox Code Playgroud)

我想替换replace_this[2, 3].更换后必须是:

a = [ 1, 2, 3, 4 ]
Run Code Online (Sandbox Code Playgroud)

更新

当然,切片可以做(对不起,我没有在问题中写出来),但问题是你可能replace_this在列表中有多个值.在这种情况下,您需要在循环中进行替换,这将变得不理想.

我认为使用它会更好itertools.chain,但我不确定.

Jon*_*nts 12

你可以使用切片:

>>> a = [ 1, 'replace_this', 4 ]
>>> a[1:2] = [2, 3]
>>> a
[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

正如@mgilson指出的那样 - 如果你碰巧不知道要替换的元素的位置,那么你可以a.index用来找到它......(见他的评论)

更新与不使用切片有关

使用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]
Run Code Online (Sandbox Code Playgroud)

  • +1 - 你可以通过`i = a.index('replace_this')得到`1:2`; a [i:i + 1] = [2,3]` (6认同)