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

Python列表使用浮点切片索引采样的通用解决方案咨询

解决方案

纯Python实现(无第三方依赖,适配示例输出)

import math

def sample_list_to_fixed_length(lst: list, target_len: int) -> list:
    original_len = len(lst)
    # 边界异常处理
    if target_len <= 0:
        raise ValueError("目标长度必须为正整数")
    # 目标长度大于等于原列表长度时直接返回原列表副本
    if target_len >= original_len:
        return lst.copy()
    # 计算浮点步长,保证采样覆盖首尾元素
    step = (original_len - 1) / (target_len - 1)
    # 生成采样索引,使用ceil取整匹配示例输出,可按需替换为round/floor
    indices = [math.ceil(i * step) if i != 0 else 0 for i in range(target_len)]
    # 按索引提取元素
    return [lst[idx] for idx in indices]

调用示例

# 输入列表
original_list = [0,2,3,7,6,8,9,15,20,30,40]
# 目标长度设为4
new_list = sample_list_to_fixed_length(original_list, 4)
print(new_list) # 输出:[0, 6, 15, 40]

可选:基于Numpy的简化实现

如果项目允许引入Numpy依赖,代码可以更简洁:

import numpy as np

def sample_list_to_fixed_length(lst: list, target_len: int) -> list:
    original_len = len(lst)
    if target_len <= 0:
        raise ValueError("目标长度必须为正整数")
    if target_len >= original_len:
        return lst.copy()
    # 直接生成等间隔整数索引
    indices = np.linspace(0, original_len-1, target_len, dtype=int)
    return [lst[idx] for idx in indices]

取整方式说明

如果不需要完全匹配示例输出,可根据业务需求调整索引的取整规则:

  • 用round():四舍五入取整,整体采样更均匀
  • 用math.floor():向下取整,不会取到超出列表范围的索引
  • 用math.ceil():向上取整,和提问中的示例输出完全匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:36:03