gruelle gruelle -4 years ago 101
Python Question

Replacing a value with anothe rone

Let's say I have 6 values

elem=[a,b,c,d,e,f]


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.

Ex.

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


now, I have something like this:

if elem[0]=0:
newelem=[elem[6],elem[1],elem[2],elem[3],elem[4]]

elif elem[1]=0:
newelem=[elem[0],elem[6],elem[2],elem[3],elem[4]]


etc...

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