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

Python嵌套字典按数值区间分组统计各区间元素数量实现问题

实现方案

方案1:纯Python输出目标字典

先明确区间判定规则和示例完全对齐:

  • 1-3:词频≤3
  • 3-5:3<词频≤5
  • 5-7:5<词频≤7
  • 7-10:7<词频≤10
  • 10+:词频>10

实现代码:

# 初始输入字典
raw_data = {
    938742158: {'car': 3, 'yes': 5, 'none': 6, 'bi': 5, 'new': 4, 'service': 2, 'color': 8, 'have': 6, 'back': 5}, 
    938735955: {'car': 5, 'my': 11, 'note': 5, 'dir': 3, 'led': 6, 'r': 3, 'line': 10}
}

def count_bucket(word_counts):
    # 初始化所有区间计数为0
    res = {'1-3': 0, '3-5': 0, '5-7': 0, '7-10': 0, '10+': 0}
    for cnt in word_counts.values():
        if cnt <= 3:
            res['1-3'] += 1
        elif cnt <= 5:
            res['3-5'] += 1
        elif cnt <= 7:
            res['5-7'] += 1
        elif cnt <= 10:
            res['7-10'] += 1
        else:
            res['10+'] += 1
    return res

# 遍历所有文本id生成结果
result = {text_id: count_bucket(counts) for text_id, counts in raw_data.items()}

打印结果和你预期完全一致:

print(result)
# 输出:{938742158: {'1-3': 2, '3-5': 4, '5-7': 2, '7-10': 1, '10+': 0}, 938735955: {'1-3': 2, '3-5': 2, '5-7': 1, '7-10': 1, '10+': 1}}

方案2:输出Pandas DataFrame格式

如果需要转为表格形式的DataFrame,追加以下代码即可:

import pandas as pd
df = pd.DataFrame.from_dict(result, orient='index')
# 可选:将文本id从索引转为普通列
df = df.reset_index().rename(columns={'index': '文本id'})
print(df)

输出效果:

文本id1-33-55-77-1010+
93874215824210
93873595522111

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 12:18:03