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

Python如何读取TXT文件中逗号分隔的数字并计算平均值

代码修改方案

核心修改点

  • 调整行处理逻辑:每行读取后先按英文逗号拆分得到单个数字字符串,逐个去除首尾空格后再转整数存入列表,适配一行多数字的存储格式
  • 修正原代码笔误:将len(last)改为len(lst),匹配列表变量名
  • 优化平均值计算逻辑:移到循环外执行,避免每读一个数字就重复计算,提升运行效率
  • 原代码开头导入的os模块没有被使用,可按需删除

修改后完整代码

def averg_int(path):
    lst = []
    with open(path, "r") as file:
        for line in file:
            # 跳过空行避免运行报错
            if not line.strip():
                continue
            # 拆分当前行的所有数字字符串
            num_str_list = line.strip().split(',')
            for num_str in num_str_list:
                n = int(num_str.strip())
                lst.append(n)
    # 所有数字读取完成后统一计算平均值
    avg = sum(lst) / len(lst)
    return avg

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:24:08