gpt4 book ai didi

python - 彼此之间重复列表元素,直到我们达到一定长度

转载 作者:行者123 更新时间:2023-11-28 19:48:19 25 4
gpt4 key购买 nike

我有一个列表,它以数字开头,结尾是 nan

[1,2,3, nan, nan, nan, nan]

我想将可用数字分布在我列表的整个长度上,直到所有 nan 都被覆盖。

我们的列表中有 nan,我们从第一个数字开始:[1, 1, 2, 3, nan, nan, nan] 列表中还有 nan 吗?是的:[1,1,2,2,3, nan, nan] ... [1,1,2,2,3,3,nan]。 .. 如果所有 nan 都被覆盖,列表将看起来像

[1,1,1,2,2,3,3]

实现此目标的最 pythonic 方法是什么?

编辑:

nan是一个numpy.nan,这个可以换成None

最佳答案

这是另一种计算每个列表元素必须重复多少次的解决方案

import itertools as it
l = [1, 2, 3, 'nan', 'nan', 'nan', 'nan']

off = l.index('nan') # offset of the first 'nan' element
subl = l[:off] # to avoid slicing more than once

rem = len(l) % off # remainder
rep = len(l) // off # min repetitions

rep_el = (rep+1 if p < rem else rep for p,el in enumerate(subl))
newl = it.chain(*(it.repeat(el,r) for el,r in zip(subl, rep_el)))

print(list(newl))

产生

[1, 1, 1, 2, 2, 3, 3]

rem 是列表中元素总数除以非'NaN'的元素个数的余数

rep 是所有元素的最小重复次数

rep_el 是一个生成器,其中包含每个列表元素必须具有的重复项。如果元素的位置小于余数,则意味着它的重复应该增加一个。

newl 是新形成的列表。它是通过将每个元素重复上面计算的正确次数而生成的重复串接起来构建的。

关于python - 彼此之间重复列表元素,直到我们达到一定长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34432056/

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