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

Python如何将Counter对象转换为与chars列表顺序长度一致的整数列表

实现方法

直接遍历指定的chars列表逐个取值即可,Counter 类型访问不存在的键时默认返回整数0,刚好匹配缺失字符填0的要求,一行代码就能完成,生成的列表完全匹配chars的顺序和长度:

result = [counter[c] for c in chars]

如果需要兼容普通字典的场景(比如后续替换为非Counter的统计结果),也可以用get方法显式指定默认值:

result = [counter.get(c, 0) for c in chars]

完整运行示例

from collections import Counter

# 给定的字符顺序列表
chars  =  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
           'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '-']
# 统计示例字符串
s = 'testing'
counter = Counter(s)

# 生成目标列表
result = [counter[c] for c in chars]

# 验证结果:长度和chars一致,为27
print(len(result) == len(chars))  # 输出 True
# 查看t字符对应的值,和统计结果一致为2
print(result[chars.index('t')])  # 输出 2
# 查看不存在的字符a对应的值,为0
print(result[0])  # 输出 0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 19:39:01