我有一个数据序列(列表),我必须调整大小。我已经为它编写了一个函数,但它非常粗糙。有没有人知道更好的方法来解决这个问题?在
在所有示例中,我的输入数据序列如下: 编辑:即使这个例子是线性的,你也不能指望序列是由公式构建的。在
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
当我将它从10个项目调整为5个项目时,我希望得到如下输出:
[1, 3, 5, 7, 9]
或{
现在,当您将数据序列的长度减半时,所有这些都不是很困难,但是输出序列的大小是可变的。我可以小于或大于原始序列的长度。在
当我把它从10个项目调整到19个项目时(很容易手动完成数字),我希望如下所示:
[1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10]
def sequenceResize(source, length):
"""
Crude way of resizing a data sequence.
Shrinking is here a lot more accurate than expanding.
"""
sourceLen = len(source)
out = []
for i in range(length):
key = int(i * (sourceLen / length))
if key >= sourceLen:
key = sourceLen - 1
out.append(source[key])
return out
结果如下:
^{pr2}$收缩是精确的,但是扩展序列就不是那么好了。在
有没有人知道一个现有的或简单的方法来妥善处理这个问题?在
你可以用np.lisnpace公司公司名称:
输出:
^{pr2}$与其直接确定索引,不如计算两个列表中索引之间的“步数”比率。注意,比列表中的元素少一个步骤。然后,您可以得到
floor
和ceil
项,并根据当前步骤的小数部分确定最终值,得到两者之间的加权平均值(见下图)。在或者稍短一点,使用
^{pr2}$divmod
:示例:
另一个例子作为例证。蓝色是原始值,红色是插值值。在
相关问题 更多 >
编程相关推荐