gruelle gruelle -4 years ago 101
Python Question

Replacing a value with anothe rone

Let's say I have 6 values


f is always !=0 but one of the others is always = 0 (one at a time).

I'd like to know how to check which of the elem[] is equal to zero and replace this value with f in a newelem.


elem=[1,2,3,0,5,6] --> newelem=[1,2,3,6,5]

now, I have something like this:

if elem[0]=0:

elif elem[1]=0:


Answer Source
>>> list(map(lambda x: x if x!=0 else elem[-1], elem))[:-1]
[1, 2, 3, 6, 5]

Or with list comprehension:

[i if i!=0 else elem[-1] for i in elem][:-1]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download