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

Python读取TXT文件计算数组均值报错及解决需求

问题描述
  • 代码:
import ast
import numpy as np

file_path = "C:/Users/USER/OneDrive - Technion/Research_Technion/Python_PNM/Basics/Velocity_Average/Test.txt"
with open(file_path) as f:
    content = f.read()
    data = ast.literal_eval(content)

for arr in data:
    arr = np.array(arr)  # Convert the array to a NumPy array
    filtered_data = arr[arr > 1e-9]  # Filter elements greater than 1e-9
    mean = np.mean(filtered_data)
    print(mean)
  • Test.txt内容:
[array([[1.0],
       [2.0],
       [3.0],
       [4.0],
       [1e-12]])]
[array([[1.0],
       [2.0],
       [3.0],
       [4.0],
       [1e-12]])]
  • 报错信息:

line 7
[array([[1.0],
^
SyntaxError: invalid syntax

  • 期望输出:[2.5, 2.5]
解决方案

问题根源有两点:

  1. Test.txt中的array(...)是NumPy专属语法,并非Python原生字面量,ast.literal_eval无法解析该格式。
  2. 文件内的两个列表彼此独立,未被包裹成一个完整的可解析Python数据结构(如大列表),直接解析会触发语法错误。

修正步骤

  1. 修改Test.txt内容:将array(...)替换为普通嵌套列表,并把两个子列表放入一个大列表中,修正后内容如下:
[
    [[1.0], [2.0], [3.0], [4.0], [1e-12]],
    [[1.0], [2.0], [3.0], [4.0], [1e-12]]
]
  1. 优化代码输出格式:原代码逻辑可正常运行,若要直接输出期望的列表格式,可调整代码如下:
import ast
import numpy as np

file_path = "C:/Users/USER/OneDrive - Technion/Research_Technion/Python_PNM/Basics/Velocity_Average/Test.txt"
with open(file_path) as f:
    content = f.read()
    data = ast.literal_eval(content)

means = []
for arr in data:
    arr = np.array(arr)
    filtered_data = arr[arr > 1e-9]
    mean = np.mean(filtered_data)
    means.append(mean)

print(means)

运行结果

执行修正后的代码,输出结果为[2.5, 2.5],完全符合期望。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 19:32:09