用python中的列表替换元素 [英] Replace element with a list in python
问题描述
在python中,用另一个列表中的元素替换列表中的元素的最佳方法是什么?
In python, what is the best way to replace an element in a list with the elements from another list?
例如,我有:
a = [ 1, 'replace_this', 4 ]
我想用[2, 3]
替换replace_this
.更换后必须是:
I want to replace replace_this
with [2, 3]
. After replacing it must be:
a = [ 1, 2, 3, 4 ]
更新
当然可以进行切片(很抱歉,我没有在问题中写它),但是问题是您可能有多个replace_this
值列表.在这种情况下,您需要循环进行替换,这将变得不理想.
Of course, it is possible to do with slicing (I'm sorry that I didn't write it in the question), but the problem is that it is possible that you have more than one replace_this
value in the list. In this case you need to do the replacement in a loop and this becomes unoptimal.
我认为使用itertools.chain
会更好,但我不确定.
I think that it would be better to use itertools.chain
, but I'm not sure.
推荐答案
您可以使用切片:
>>> a = [ 1, 'replace_this', 4 ]
>>> a[1:2] = [2, 3]
>>> a
[1, 2, 3, 4]
正如@mgilson所指出的-如果您不知道要替换的元素的位置,则可以使用a.index
来查找它...(请参阅他的评论)
And as @mgilson points out - if you don't happen to know the position of the element to replace, then you can use a.index
to find it... (see his comment)
与不使用切片有关的更新
使用itertools.chain
,确保replacements
具有可迭代项:
Using itertools.chain
, making sure that replacements
has iterables:
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]
这篇关于用python中的列表替换元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!