from itertools import accumulate
Headings = ['Doug', None, None, None, None, 1234, None, None, 'Mike', None]
Headings = accumulate(Headings,lambda x, y: x if y is None else y)
['Doug', 'Doug', 'Doug', 'Doug', 'Doug', 1234, 1234, 1234, 'Mike', 'Mike']
如果您还想要索引,则可以使用此answer的变体:
from itertools import chain
Headings = ['Doug', None, None, None, None, 1234, None, None, 'Mike', None]
def replace_none(l):
inds = ((ind, ele) for ind, ele in enumerate(Headings) if ele is not None)
start_i, start_ele = next(inds)
yield start_i
yield from chain.from_iterable(((i-1, i) for i, _ in inds))
for ind, ele in enumerate(l):
if ele is None:
Headings[ind] = start_ele
else:
start_ele = ele
输出:
print(list(replace_none(Headings)))
print(Headings)
[0, 4, 5, 7, 8]
['Doug', 'Doug', 'Doug', 'Doug', 'Doug', 1234, 1234, 1234, 'Mike', 'Mike']
如果第一个元素可能是None,并且您希望在第一个不是None的元素之前使用前一个None:
def replace_none(l):
inds = ((ind, ele) for ind, ele in enumerate(Headings) if ele is not None)
start_i, start_ele = next(inds)
if start_i == 0:
yield start_i
else:
yield from (start_i-1, start_i)
yield from chain.from_iterable(((i-1, i) for i, _ in inds))
for ind, ele in enumerate(l):
if ele is None:
Headings[ind] = start_ele
else:
start_ele = ele