问题描述
我想知道代码中是否已在某个位置定义了数组.像 a.exist()
这样的东西在存在时给出True,在不存在时给出False.
I want to know if an array is already defined somewhere before in the code.Something like a.exist()
gives True if it exists and False if it doesn't.
我尝试了 a.size:
,但如果该数组尚不存在,则会显示一条错误消息,我想避免.
I tried a.size:
, but if the array doesn't exist yet, it gives an error message, which I want to avoid.
如果您想知道的话,要求这样做的情况是循环发生的.
The situation demanding this happened in a loop, if you are wondering.
推荐答案
Python有一些内置函数,如果在当前/本地/全局范围内分配了变量,这些函数可以取消.
Python has some builtin-functions that can ckeck if a variable is assigned in the current/local/global scope.
例如要检查是否在当前本地scopy中定义了变量,请使用:
For example to check if a variable is defined in the current local scopy use:
if 'a' in dir():
# Variable a is defined.
if hasattr(a, 'shape'):
# Probably a numpy array, at least it has a shape.
但这不是很好的python, try/except
更常见,但是出于完整性考虑,我认为值得一提的是,您无需任何try/except就可以做到这一点.
But that's not good python, try/except
is more common but for completness I thought it worth mentioning that you can do it without any try/except.
if 'a' in dir():
print('yes')
else:
print('no')
# prints 'no' because we haven't defined any variable a
a = np.array([1,2,3])
if 'a' in dir():
print('yes')
else:
print('no')
# prints 'yes' because I defined it
del a
if 'a' in dir():
print('yes')
else:
print('no')
# prints 'no' because I deleted the variable again
Also worth mentioning is locals
and globals
.
这篇关于如何检查numpy数组是否已经存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!