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

如何直接用字典统计单词列表中各索引位置的字母出现次数

解决方案

可以直接在单词列表中完成各索引位置的字母次数统计,无需单独生成字母列表,具体实现步骤如下:

  1. 先将单词列表按长度从长到短排序,确定需要处理的索引范围(由最长单词的长度决定)
  2. 遍历每个索引位置,直接从符合长度要求的单词中提取对应字母并统计次数

示例代码

from collections import Counter

main_list = ['elephant','mouse','tiger','dog']
# 按单词长度降序排序
sorted_words = sorted(main_list, key=lambda x: len(x), reverse=True)
max_len = len(sorted_words[0])
result_list = []

for idx in range(max_len):
    # 直接收集当前索引的有效字母(单词长度需大于当前索引)
    current_chars = [word[idx] for word in sorted_words if len(word) > idx]
    # 统计次数并转为字典存入结果列表
    result_list.append(dict(Counter(current_chars)))

print(result_list)

代码说明

  • sorted(main_list, key=lambda x: len(x), reverse=True):通过单词长度降序排序,确保最长单词的长度作为索引处理的上限
  • 循环遍历每个索引idx,用列表推导式直接从排序后的单词中提取对应位置的字符(跳过长度不足的单词)
  • Counter(current_chars)自动完成字母次数统计,转成字典后加入结果列表

运行后输出结果与示例要求一致:

[{'e': 1, 'm': 1, 't': 1, 'd': 1}, {'l': 1, 'o': 2, 'i': 1}, {'e': 1, 'u': 1, 'g': 2}, {'p': 1, 'u': 1, 'e': 1}, {'h': 1, 's': 1, 'r': 1}, {'a': 1}, {'n': 1}, {'t': 1}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 10:30:50