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

如何将Counter中的整数键转换为字符串键?

将Counter的整数键转换为字符串键

你可以通过以下几种方式实现:

方法一:使用字典推导式生成新Counter

直接遍历原Counter的键值对,把整数键转为字符串后构建新的Counter对象:

from collections import Counter

original_counter = Counter({0: 335251, 1: 31430})
str_key_counter = Counter({str(key): value for key, value in original_counter.items()})

执行后str_key_counter的结果为:Counter({'0': 335251, '1': 31430})

方法二:在原Counter上直接修改

如果需要在原对象上更新键的类型,先把原键转为列表(避免遍历过程中字典结构变化引发错误),再将整数键转为字符串后替换:

from collections import Counter

original_counter = Counter({0: 335251, 1: 31430})
for key in list(original_counter.keys()):
    original_counter[str(key)] = original_counter.pop(key)

执行后original_counter的键会直接变为字符串类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:01:04