查找和替换列表中的元素 [英] finding and replacing elements in a list

查看:57
本文介绍了查找和替换列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]

这篇关于查找和替换列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆