Hey
I have to search through a list and replace all occurrences of one element with another. I know I have to first find the index of all the elements, and then replace them, but my attempts in code are getting me nowhere. Any suggestions?
Hey
I have to search through a list and replace all occurrences of one element with another. I know I have to first find the index of all the elements, and then replace them, but my attempts in code are getting me nowhere. Any suggestions?
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]
>>> a=[1,2,3,4,5,1,2,3,4,5,1]
>>> item_to_replace = 1
>>> replacement_value = 6
>>> indices_to_replace = [i for i,x in enumerate(a) if x==item_to_replace]
>>> indices_to_replace
[0, 5, 10]
>>> for i in indices_to_replace:
... a[i] = replacement_value
...
>>> a
[6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6]
>>>
>>> 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]
List comprehension works well--and looping through with enumerate can save you some memory (b/c the operation's essentially be doing in place).
There's also functional programming...see usage of map:
>>> a = [1,2,3,2,3,4,3,5,6,6,5,4,5,4,3,4,3,2,1] >>> map(lambda x:x if x!= 4 else 'sss',a) [1, 2, 3, 2, 3, 'sss', 3, 5, 6, 6, 5, 'sss', 5, 'sss', 3, 'sss', 3, 2, 1]
I apologize but this sounds like a homework problem. We have a policy on these: http://meta.stackoverflow.com/questions/10811/homework-on-stackoverflow
However, what I would suggest is that you post the code you tried that failed and show why you think it failed and/or where the problem is, and people will be more willing to help you out.
For example, if you've barely begun your assignment or looked at Python and its data structures, you'll have a tough time with all the suggestions posted here so far.