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

Python优化字典字符串值转唯一编号:200万数据提速需求

高效实现字符串转唯一编号优化方案

问题背景

现有200万条结构如下的记录,需要将字典中的字符串值转换为唯一编号,并生成对应的查找字典,以此减小文件体积:

[
    {
        'a' : ['one','two'],
        'b' : 'fine',
        'c' : ['help']
    },
    {
        'a' : ['four','hen'],
        'b' : 'happy',
        'c' : ['mouse']
    },
    {
        'a' : ['two','hen'],
        'b' : 'fine'
    },
    ......
]

原实现代码执行耗时约1小时,目标输出格式如下:

[
    {'a' : [1,2], 'b':[3], 'c':[4]},
    {'a' : [5,6], 'b':[7], 'c':[8]},
    {'a':[2,6], 'b':[3]}
]

原代码性能瓶颈

原代码的核心低效点:

  • 使用列表dataR判断字符串是否存在,if l not in dataR是O(n)时间复杂度,百万级数据下会导致指数级耗时
  • 循环内部重复执行d[key] = [dataRD.get(x,x) for x in d[key]],同一个字段会被多次遍历修改,存在冗余操作
  • 手动维护cin、ctr变量,增加了不必要的操作和出错风险

优化方案

利用Python字典的O(1)查找特性,分阶段完成字符串收集与编号替换,大幅提升效率。

基础优化代码

def convert_data_to_number(newdata):
    str_to_id = {}
    current_id = 1
    # 第一阶段:遍历所有数据,为所有新字符串分配唯一ID
    for d in newdata:
        for key, val in d.items():
            if isinstance(val, list):
                for s in val:
                    if s not in str_to_id:
                        str_to_id[s] = current_id
                        current_id += 1
            elif isinstance(val, str):
                if val not in str_to_id:
                    str_to_id[s] = current_id
                    current_id += 1
    # 第二阶段:统一将字符串替换为对应编号
    for d in newdata:
        for key, val in d.items():
            if isinstance(val, list):
                d[key] = [str_to_id[s] for s in val]
            elif isinstance(val, str):
                d[key] = [str_to_id[val]]
    return str_to_id, newdata

性能提升核心点

  1. 字典O(1)查找替代列表O(n)判断:将字符串存在性检查的时间复杂度从线性降到常数,这是性能提升的关键
  2. 分阶段处理:先一次性完成所有字符串的编号分配,再统一替换,避免原代码中边遍历边修改的冗余操作
  3. 简化变量逻辑:用current_id自增直接分配编号,去掉多余的cin变量,减少操作步骤与出错概率

进阶优化(超大数据量场景)

如果数据量远超200万,可以先批量提取所有字符串再分配编号,逻辑更清晰:

from collections import defaultdict

def convert_data_to_number_optimized(newdata):
    # 批量提取所有字符串
    all_strings = []
    for d in newdata:
        for val in d.values():
            if isinstance(val, list):
                all_strings.extend(val)
            elif isinstance(val, str):
                all_strings.append(val)
    # 为去重后的字符串分配唯一ID
    str_to_id = defaultdict(int)
    current_id = 1
    for s in all_strings:
        if s not in str_to_id:
            str_to_id[s] = current_id
            current_id += 1
    # 统一替换字符串为编号
    for d in newdata:
        for key, val in d.items():
            if isinstance(val, list):
                d[key] = [str_to_id[s] for s in val]
            elif isinstance(val, str):
                d[key] = [str_to_id[val]]
    return dict(str_to_id), newdata

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 01:39:32