You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按比例扩展或压缩列表,保留原有值的分布比例?

问题描述

我有如下列表:

original_list = [10, 10, 2, 11, 11]

这些数值代表状态,我需要将列表按比例拉伸/压缩到指定长度:

  • 扩展时,按原列表元素的分布比例填充,比如扩展至长度10(原长度的2倍),结果应为:
    [10, 10, 10, 10, 2, 2, 11, 11, 11, 11]
    
    原列表中2个10扩展为4个,以此类推,顺序保持不变。
  • 同时需要支持缩小列表的场景。

我自己已经实现了自定义函数:

def stretch_list(lst, length): 
    new_lst = []                                                                                                                                                    
    ratio = len(lst) / length
    for i in range(length):                                                                                                                                         
        index = int(i * ratio)
        new_lst.append(lst[index])
    return new_lst

original_list = [10, 10, 2, 11, 11]
stretched_list = stretch_list(original_list, 10)

也可以用列表推导式简化(可读性稍差):

new_length = 10
stretched_list = [original_list[int(i*len(original_list)/new_length)] for i in range(new_length)]

但我想知道有没有针对此类操作的专用库方法?我试过numpy.resize和numpy.interp,都不适用:resize只是重复原数组生成副本,interp会生成插值新值,不符合需求。


可用的库实现方案

NumPy 实现

你可以用NumPy的向量化索引操作实现,逻辑和自定义函数一致,但性能更优:

import numpy as np

original_arr = np.array([10, 10, 2, 11, 11])
new_length = 10

ratio = len(original_arr) / new_length
# 生成映射到原数组的索引,向下取整保证比例匹配
indices = np.floor(np.arange(new_length) * ratio).astype(int)
stretched_arr = original_arr[indices].tolist()

# 输出结果:[10, 10, 10, 10, 2, 2, 11, 11, 11, 11]

Pandas 辅助实现

如果用Pandas处理数据,可以借助区间划分来分配索引:

import pandas as pd

original_series = pd.Series([10, 10, 2, 11, 11])
new_length = 10

# 把新长度的位置划分为和原列表长度一致的区间,获取对应索引
bins = pd.cut(np.arange(new_length), bins=len(original_series), labels=False)
stretched_series = original_series.iloc[bins].tolist()

总结

目前没有专门针对这类"保持状态分布的拉伸/压缩"的专用库,但用NumPy或Pandas的基础功能就能高效实现需求,尤其是处理大规模数据时,比纯Python循环的性能提升明显。

内容的提问来源于stack exchange,提问作者antun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 04:10:22