用python中的列表替换元素

编程入门 行业动态 更新时间:2024-10-25 12:27:41
本文介绍了用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中的列表替换元素

本文发布于:2023-11-10 15:45:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575786.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   列表   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!