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

Python是否有默认数据结构实现字符串键映射自增整数?

实现字符串到自增整数映射的方案

Python标准库里没有直接提供这种开箱即用的数据结构,但用现有工具就能快速实现,比手动维护计数器+字典更简洁:

方案1:自定义类(最贴合需求)

用dict存储映射关系,搭配itertools.count自动生成递增整数,封装成类后用法完全符合你的示例:

from itertools import count

class AutoIncrementDS:
    def __init__(self):
        self._counter = count()
        self._mapping = {}
    
    def add(self, key):
        if key not in self._mapping:
            self._mapping[key] = next(self._counter)
        return self._mapping[key]
    
    def get(self, key):
        return self._mapping.get(key)

# 测试示例
text = ['hello', 'world', 'again']
ai_ds = AutoIncrementDS()
print(ai_ds.add(text[0]))  # 输出0
print(ai_ds.add(text[1]))  # 输出1
print(ai_ds.get(text[0]))  # 输出0

这个类的add方法会给新字符串分配自增整数,重复添加同一个字符串会返回已有的值,get方法用来查询对应的值。

方案2:用defaultdict快速实现

如果不想写类,也可以用collections.defaultdict配合itertools.count,不过要注意直接访问不存在的键会自动分配新值:

from itertools import count
from collections import defaultdict

counter = count()
ai_ds = defaultdict(lambda: next(counter))

# 测试示例
text = ['hello', 'world', 'again']
print(ai_ds[text[0]])  # 输出0
print(ai_ds[text[1]])  # 输出1
print(ai_ds.get(text[0]))  # 输出0

这种方式更简洁,但如果不小心访问了未添加过的键,会自动生成新的自增值,适合对键的访问有明确控制的场景。

方案3:固定集合用Enum

如果你的字符串列表是固定不变的,不需要动态添加新字符串,可以用enum.Enum来定义,自动生成整数枚举值:

from enum import Enum, auto

class TextEnum(Enum):
    hello = auto()
    world = auto()
    again = auto()

print(TextEnum.hello.value)  # 默认从1开始,要从0开始可以加start=0参数

这个方案不支持动态添加新键,只适合预先知道所有字符串的场景。

内容的提问来源于stack exchange,提问作者adib.mosharrof

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:16:04