Replace None in the list with the smallest value none none

Considering

a = [None,1,2,3,None,4,None,None] 

I would like to

 a = [None,1,2,3,3,4,4,4] 

Currently, I rudely forced him:

 def replaceNoneWithLeftmost(val): last = None ret = [] for x in val: if x is not None: ret.append(x) last = x else: ret.append(last) return ret 

Finally, I would like to get

 a = [1,1,2,3,3,4,4,4] 

running this right to the left. I am currently

 def replaceNoneWithRightmost(val): return replaceNoneWithLeftmost(val[::-1])[::-1] 

I'm not fussy about the place or creating a new list, but now it smells to me. I don’t see a way to save the temporary β€œlast” value and use map / lambda, and nothing else comes to mind.

+6
source share
4 answers
 a = [None,1,2,3,None,4,None,None] start = next(ele for ele in a if ele is not None) for ind, ele in enumerate(a): if ele is None: a[ind] = start else: start = ele print(a) [1, 1, 2, 3, 3, 4, 4, 4] 

You also only need to set the start of the value if the first element is None:

 if a[0] is None: start = next(ele for ele in a if ele is not None) for ind, ele in enumerate(a): if ele is None: a[ind] = start else: start = ele print(a) 
+2
source

IIUC, you can use itertools.accumulate to create a forward fill:

 >>> from itertools import accumulate >>> a = [None,1,2,3,None,4,None,None] >>> list(accumulate(a, lambda x,y: y if y is not None else x)) [None, 1, 2, 3, 3, 4, 4, 4] 
+4
source

Here is some code that will do what you need if you don't want it in place, just pass it list(my_list) instead of my_list .

 def replaceNoneWithLeftmost(val): for i in range(len(val)): if val[i] is None: for j in range(i-1, -1, -1): if val[j] is not None: val[i] = val[j] break for i in range(len(val)): if val[i] is None: for j in range(i+1, len(val)): if val[j] is not None: val[i] = val[j] break return val 

Also, if you are using python2, use xrange instead of range .

0
source
 a = [None,1,2,3,None,4,None,None] first = True for i in range(len(a)): if first: if a[i] != None: a[:i] = [a[i] for _ in range(i)] first = False if a[i] == None: a[i] = a[i-1] print a 

OUT:

 [1, 1, 2, 3, 3, 4, 4, 4] 
0
source

All Articles