Python构建动物信息字典时如何剥离换行符并访问元组属性
代码修正方案
- 核心问题修复点:
- 循环前初始化空字典
animal_dict = {}(原代码遗漏该步,运行会触发NameError) - 读取每行后先剥离行尾换行符,再做分割
- 分割后的每个字段单独调用
.strip()去除首尾多余空格,避免键值带空白导致匹配失败 - 用
with语句管理文件句柄,自动处理关闭逻辑,避免资源泄漏
- 循环前初始化空字典
- 修正后可直接运行的代码:
def read_animals_from_file(file_name): ''' Makes a dictionary with the animals as keys and their attributes as values :param file_name: Name of the file with information :return: Dictionary with the animals and their attributes ''' animal_dict = {} with open(file_name, "r") as fobj: for line in fobj: line = line.rstrip('\n') # 分割后批量去除每个字段首尾空白 key, value1, value2, value3, value4 = [item.strip() for item in line.split("/")] animal_dict[key] = (value1, int(value2), int(value3), value4) print(animal_dict) return animal_dict
元组值访问方法
- 你的判断正确:每个动物对应的属性值是tuple类型,字段顺序完全匹配文件行的定义:
元组索引对应关系
- 0:hibernation(冬眠状态)
- 1:wake_up_time(苏醒时间)
- 2:sleep_time(入睡时间)
- 3:feeding_time(进食时间)
- 元组通过索引下标取值,索引从0开始计数。如果要获取
Bear的苏醒时间,直接按下标取即可:
# 先运行函数拿到字典 animal_info = read_animals_from_file("你的数据文件路径.txt") # 取Bear对应的元组,索引1就是苏醒时间 bear_wake_up_time = animal_info["Bear"][1] # 直接打印结果 print(bear_wake_up_time) # 输出9
内容的提问来源于stack exchange,提问作者mat3ilda
相关产品推荐
相关产品推荐

