Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

python - 查找和替换列表中的元素(finding and replacing elements in a list)

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]

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

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

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

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

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

  ask by James translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try using a list comprehension and the ternary operator .

(尝试使用列表推导三元运算符 。)

>>> a=[1,2,3,1,3,2,1,1]
>>> [4 if x==1 else x for x in a]
[4, 2, 3, 4, 3, 2, 4, 4]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...