python列表的替代_使用前面的非None项替换python列表中的None值?

这段代码展示了如何利用`itertools.accumulate`和`chain.from_iterable`在列表中填充和替换None值,确保连续的None值被前一个非None值替代。同时,提供了在处理第一个元素可能是None的情况下的解决方案。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值