Python如何仅用推导式生成存储单词ASCII码列表的字典
正确实现方案
原有代码问题
- docstring没有正确缩进,不符合PEP8规范
- 错误使用列表推导式,需求要求生成字典,应使用字典推导式
- 迭代逻辑错误:
for x in word in words语法不合法,正确逻辑应先遍历输入的单词列表,再遍历单个单词的每个字符 - 调用函数错误:获取字符ASCII值应使用
ord()内置函数,而非ascii() - 缺少return语句,函数无法返回生成的结果
- 多余调用
print(),与需求无关
正确代码
def get_word_codes(words): """Given a list of words, return a dictionary where the words are keys, and the value for each key is a list of the character codes of the letters of the word that is its key.""" return {word: [ord(char) for char in word] for word in words}
代码说明
- 完全基于推导式实现:外层字典推导式遍历输入的单词列表生成键值对,值的部分通过列表推导式遍历单词的每个字符生成对应的ASCII值列表
- 推导式外无任何for循环,符合要求
- 缩进、命名、docstring格式全部符合PEP8规范
运行验证
# 测试1 words = ['yes', 'no'] codes = get_word_codes(words) print(codes) # 输出:{'yes': [121, 101, 115], 'no': [110, 111]} # 测试2 words = ['hello', 'python', 'bye'] codes = get_word_codes(words) print(codes) # 输出:{'hello': [104, 101, 108, 108, 111], 'python': [112, 121, 116, 104, 111, 110], 'bye': [98, 121, 101]} # 测试3 codes = get_word_codes(['Python is fun!']) print(codes) # 输出:{'Python is fun!': [80, 121, 116, 104, 111, 110, 32, 105, 115, 32, 102, 117, 110, 33]}
内容的提问来源于stack exchange,提问作者user12916095
相关产品推荐
相关产品推荐

