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

Python中用循环与range实现3个评分分箱的问题求助

评分分箱统计问题解决方法

本人为数据分析新手,尝试在Python中创建3个评分分箱,分箱规则为:Negative(1-5分)、Neutral(6-8分)、Positive(9-10分)。要求遍历score_list并输出三条分箱统计语句,但现有代码输出未按3个分箱展示,附上代码寻求解决方法:

原代码:

# Define a function score_counter

score_list = [1,2,3,4,5,6,7,8,9,10]
for score_counter in range(1, 11):
    if score_counter <= (5):
        print('Negative: ' + str(score_counter))
    elif score_counter == (6):
        print('Neutral: ' + str(score_counter))
    elif score_counter == (7):
        print('Neutral: ' + str(score_counter))
    elif score_counter == (8):
        print('Neutral: ' + str(score_counter))
    else:
        print('Positive: '+ str(score_counter))
    print()

问题原因

原代码每遍历一个分数就打印一次,导致每个分数单独输出,无法实现按分箱汇总的效果;同时条件判断冗余,逐个判断6、7、8完全没必要。

修正后的代码

# 初始化三个分箱容器,用于存储对应区间的分数
negative = []
neutral = []
positive = []

score_list = [1,2,3,4,5,6,7,8,9,10]

# 遍历分数,归类到对应分箱
for score in score_list:
    if 1 <= score <= 5:
        negative.append(score)
    elif 6 <= score <= 8:
        neutral.append(score)
    elif 9 <= score <= 10:
        positive.append(score)

# 输出三条分箱统计语句
print(f'Negative: {negative} (共{len(negative)}个分数)')
print(f'Neutral: {neutral} (共{len(neutral)}个分数)')
print(f'Positive: {positive} (共{len(positive)}个分数)')

代码说明

  1. 先创建三个空列表,分别对应三个分箱,用来存储对应区间的分数
  2. 遍历score_list,通过区间判断将每个分数分配到对应分箱
  3. 最后统一输出每个分箱的分数列表和数量,直接得到三条符合要求的统计语句

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:25:15