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

Python循环内用if语句给字典赋值时计数异常问题排查

问题排查与修复

核心Bug:数组元素替换逻辑错误

你用np.insert()的方式并非替换数组元素,而是往数组里插入新元素。原本的array_type是1500个0,插入500个1后,数组总长度变成了1500+500=2000,完全偏离了你想要的1500长度数组。后续循环仅遍历前1500个元素,统计结果自然和预期不符。

修复后的完整代码

把元素替换逻辑改成直接通过索引赋值,确保数组长度始终是1500:

import numpy as np
# 创建包含1500个0的数组
array_type = np.zeros(1500)
# 随机选择500个不重复的索引(replace=False避免重复选中同一位置)
selected_indices = np.random.choice(len(array_type), size=500, replace=False)
# 将选中的索引位置设为1
array_type[selected_indices] = 1

beta = 0.01 
counter = {0: 0, beta: 0}
test_dict = {}

for indx in range(1500):
    if array_type[indx] == 1.0:
        test_dict[indx] = beta
        counter[beta] += 1
    else:
        test_dict[indx] = 0.0
        counter[0] += 1

print(counter)  # 此时会输出预期的{0:1000, 0.01:500}

额外优化建议

可以用numpy的向量化操作替代手动循环,代码更简洁且效率更高:

# 直接生成test_dict
test_dict = dict(enumerate(np.where(array_type == 1, beta, 0)))
# 直接统计次数
counter = {0: (array_type == 0).sum(), beta: (array_type == 1).sum()}

内容的提问来源于stack exchange,提问作者CaffèSospeso

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 05:44:54