You need to enable JavaScript to run this app. Python构建动物信息字典时如何剥离换行符并访问元组属性
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 16:24:04