我正在尝试使用exec和eval函数编写代码以从numpy .npz文件读取变量列表。
查看上一篇文章: 在迈克尔·布彻(Michael Butscher)的帮助下 exec name "templet_1h" is not defined ,该功能现在正在运行。但是,我遇到了另一个尴尬的情况。
在执行函数类型(read_file)之前,我执行的函数是函数“ numpy.ndarry”。
有人可以帮我解释一下吗?如何解决?
def read_file(file_names_2):
global templet_1h
import numpy as np
Delete_elements=["arr_0"]
evaluate_1= "templet_1h=np.load(\"./" +file_names_2+ ".npz\")";
exec(evaluate_1,globals())
for i in (templet_1h.files):
if not ( (i in Delete_elements) ):
evaluate_2= i+"="+"templet_1h[\"" + i + "\"]";
exec(evaluate_2,globals())
del templet_1h
return
答案 0 :(得分:0)
numpy.ndarray
是numpy为使用numpy函数进行计算而创建的类类型
要将其转换为最可用的list
:
import numpy as np
x = np.ndarray([1,2])
x = x.tolist()
答案 1 :(得分:0)
对此行为的唯一可能解释是,您有一个名为read_file
的文件,该文件已添加到templet_1h
中。
在循环访问templet_1h.files
时,有时会调用以下内容:
evaluate_2= i+"="+"templet_1h[\"" + i + "\"]";
# this results in: read_file = templet_1h["read_file"]
执行此操作后,它将read_file
重新绑定到全局名称空间中的numpy数组中,而不是您的函数中。
虽然有多种方法可以解决此问题,但 real 问题是,您不应该以这种方式使用exec
。执行任意python代码很危险,并且此特定代码段非常容易滥用。例如,如果用户决定创建文件名'np.argmax'
,则您将失去调用argmax
函数的能力,该列表将一直存在。
您应该真正使用字典之类的东西来存储可变数量的变量,而不要依赖危险行为。