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

标签 python numpy

我有一个列表,它以数字开头,结尾是 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/

相关文章:

Python:如何添加对象的静态类数组?

python - 根据数据框制作 2 个变量的条形图

python - 如何使用具有大量行的 DataFrame 使线图可读

python - 在python中计算PCA的欧氏距离

PHP 与 django 一起在 heroku 实例中

python - 属性错误 : install_layout when attempting to install a package in a virtual environment

python - Pandas 每行获得前 n 列

python - 从大型数据集高效创建二维直方图

python - 为数组 A 中的唯一值获取数组 B 中的 NumPy 数组索引,对于两个数组中存在的值,与数组 A 对齐

python - 获取 Pandas 数据框中的节点祖先