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

使用random.choices触发ValueError:权重与样本集数量不匹配求助

问题解决:random.choices权重与样本集不匹配的报错

核心错误原因

你代码里的致命问题是调用random.choices时,把列表alphabet转成了字符串str(alphabet)。列表转字符串后,population变成了字符串的每个字符(比如列表['0','1']转字符串后是"['0', '1']",长度为8),这和你补全后的new_w长度完全不匹配,自然触发ValueError。

修正后的代码

import random
import time

def get_random_unicode(length, w):
    try:
        get_char = unichr
    except NameError:
        get_char = chr

    # 定义要采样的Unicode码点范围
    include_ranges = [(0x0030, 0x0039), (0x30A0, 0x30FF)]

    alphabet = [
        get_char(code_point) for current_range in include_ranges
            for code_point in range(current_range[0], current_range[1] + 1)
    ]
    new_w = w.copy()  # 复制原列表避免修改外部传入的权重
    while len(new_w) < len(alphabet):
        new_w.append(1)  # 用append补全权重,比列表拼接更高效
    # 提前验证长度匹配,方便调试
    assert len(alphabet) == len(new_w), "权重与样本集长度不匹配"
    # 直接传入alphabet列表,不要转成字符串
    return random.choices(alphabet, weights=new_w, k=length)

start_time = time.time()
print(get_random_unicode(5, [10,10]), end=" ")

额外优化说明

  • 用copy()复制权重列表,避免修改外部传入的原始权重数据
  • 用append()补全权重,比new_w = new_w + [1]的列表拼接效率更高
  • 添加assert语句提前校验长度,能快速定位调试时的异常情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:40:35