如何实现从单词列表指定索引提取字母并统计至字典?
按指定索引提取单词字母并统计次数
我有一个单词列表,需求是从每个单词的指定索引位置提取字母,存入字典并统计对应字母的出现次数。举例:
- 若单词列表为
["carrot", "sky", "house", "picture"],提取索引0的字母,结果是{"c":1, "s":1, "h":1, "p":1} - 提取索引1的字母,结果是
{"a":1, "k":1, "o":1, "i":1}
我尝试了以下代码,但它统计的是列表中所有单词的全部字母,不符合需求:
for el in list: for x in el: dictionary[x] = dictionary.get(x, 0) + 1 return dictionary
正确实现方式
核心是只提取每个单词指定索引的字母,而非遍历单词的全部字符。
基础循环实现
def count_target_index_chars(word_list, target_index): count_dict = {} for word in word_list: # 避免单词长度不足导致索引越界 if len(word) > target_index: char = word[target_index] count_dict[char] = count_dict.get(char, 0) + 1 return count_dict # 测试示例 test_words = ["carrot", "sky", "house", "picture"] print(count_target_index_chars(test_words, 0)) # 输出: {'c': 1, 's': 1, 'h': 1, 'p': 1} print(count_target_index_chars(test_words, 1)) # 输出: {'a': 1, 'k': 1, 'o': 1, 'i': 1}
用collections.defaultdict简化代码
如果不想每次调用get()方法设置默认值,可以用defaultdict自动处理初始计数:
from collections import defaultdict def count_target_index_chars(word_list, target_index): count_dict = defaultdict(int) for word in word_list: if len(word) > target_index: char = word[target_index] count_dict[char] += 1 # 转换为普通字典返回,保持示例格式一致 return dict(count_dict)
关键改进说明
- 移除了遍历单词所有字母的内层循环,直接通过
word[target_index]定位目标字符 - 增加长度判断,防止因单词过短触发索引越界异常
内容的提问来源于stack exchange,提问作者Zhansaya
相关产品推荐
相关产品推荐

