查找和替换列表中的元素

编程入门 行业动态 更新时间:2024-10-25 20:23:54
本文介绍了查找和替换列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我必须搜索一个列表,然后用一个元素替换所有出现的元素.到目前为止,我在代码方面的尝试使我无处可寻,那么做到这一点的最佳方法是什么?

I have to search through a list and replace all occurrences of one element with another. So far my attempts in code are getting me nowhere, what is the best way to do this?

例如,假设我的列表包含以下整数

For example, suppose my list has the following integers

>>> a = [1,2,3,4,5,1,2,3,4,5,1]

我需要将所有出现的数字1替换为值10,所以我需要的输出是

and I need to replace all occurrences of the number 1 with the value 10 so the output I need is

>>> a = [10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]

因此,我的目标是将数字1的所有实例替换为数字10.

Thus my goal is to replace all instances of the number 1 with the number 10.

推荐答案

>>> a= [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1] >>> for n, i in enumerate(a): ... if i == 1: ... a[n] = 10 ... >>> a [10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]

更多推荐

查找和替换列表中的元素

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

发布评论

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

>www.elefans.com

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