简体   繁体   English

用python中的列表替换元素

[英]Replace element with a list in python

In python, what is the best way to replace an element in a list with the elements from another list? 在python中,用另一个列表中的元素替换列表中的元素的最佳方法是什么?

For example, I have: 例如,我有:

a = [ 1, 'replace_this', 4 ]

I want to replace replace_this with [2, 3] . 我想用[2, 3]替换replace_this After replacing it must be: 更换后必须是:

a = [ 1, 2, 3, 4 ]

Update 更新

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. 当然,切片可以做(对不起,我没有在问题中写出来),但问题是你可能在列表中有多个replace_this值。 In this case you need to do the replacement in a loop and this becomes unoptimal. 在这种情况下,您需要在循环中进行替换,这将变得不理想。

I think that it would be better to use itertools.chain , but I'm not sure. 我认为使用itertools.chain会更好,但我不确定。

You can just use slicing: 你可以使用切片:

>>> a = [ 1, 'replace_this', 4 ]
>>> a[1:2] = [2, 3]
>>> a
[1, 2, 3, 4]

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

update related to not using slicing 更新与不使用切片有关

Using itertools.chain , making sure that replacements has iterables: 使用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]

I would go with a generator to replace the elements, and another generator to flatten it. 我会用发电机来替换元件,然后用另一台发电机来压扁它。 Assuming you have a working flatten generator, such that in the link provided: 假设您有一个工作flatten生成器,在提供的链接中:

def replace(iterable, replacements):
    for element in iterable:
        try:
            yield replacements[element]
        except KeyError:
            yield element

replac_dict = {
    'replace_this': [2, 3],
    1: [-10, -9, -8]
}
flatten(replace(a, replac_dict))
# Or if you want a list
#list(flatten(replace(a, replac_dict)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM