gpt4 book ai didi

python - 使用值作为断点来分解列表?

转载 作者:太空宇宙 更新时间:2023-11-04 08:48:09 25 4
gpt4 key购买 nike

我有一个列表,其中包含一些值,每个值后跟一些 Nones:

['Apple', None, None, None, None, None, None, 'Orange', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'Pear', None, None, None, None, None, None, None, 'Banana', None, None]

我想要这样的输出,它将列表分成单独的列表,每个列表都以非 None 值作为断点:

['Apple', None, None, None, None, None, None] 
['Orange', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]
['Pear', None, None, None, None, None, None, None]
['Banana', None, None]

我正在为如何去做而绞尽脑汁。

最佳答案

你说你想用最新的非 None 值替换 None。我将跳过“如何拆分”问题,并回答“替换”问题:

def fill_nones(seq):
last = None
for val in seq:
if val is not None:
last = val
yield last

现在您可以创建一个新列表:

filled = list(fill_nones(old_list))

关于python - 使用值作为断点来分解列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38105620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com