繁体   English   中英

检查python中是否存在多个变量

[英]Check whether multiple variables exist in python

我想检查 python 中是否存在多个变量。 我尝试了一些方法,但我不知道为什么这在 Python 中不起作用。

这是我的 Python 代码,我在 if 条件中使用“全部”

feature = [{'a':'A'}]
table = 'demo'
if all(var in locals() for var in ('feature', 'table')):
    print("all exist")
else:
    print("at least one not exists")

这个 output 应该是“全部存在”,而结果是“至少一个不存在”,这让我很困惑。

The problem is that you passed a generator function as the argument to the all function, so locals() is being called in that generator function's local scope, not the scope you called all from (where feature and table are defined).

要诊断这个错误,我们可以试试这个:

>>> all(print(locals()) for var in ('feature', 'table'))
{'var': 'feature', '.0': <tuple_iterator object at 0x7fef8edc27f0>}

请注意生成器函数的 scope 中的局部变量是var (保存要检查的键)和.0保存对元组上的迭代器的引用('feature', 'table') 这些是唯一需要进行迭代的本地人。

为了解决这个问题,从右边的 scope 调用locals()

feature = [{'a':'A'}]
table = 'demo'

outer_locals = locals()

if all(var in outer_locals for var in ('feature', 'table')):
    print("all exist")
else:
    print("at least one not exists")

正如预期的那样,Output 现在“全部存在”。

locals有时不提供您想要的 dict,当它位于定义变量的同一 scope 中时,即globals将在这里工作:

feature = [{'a':'A'}]
table = 'demo'

if all(var in globals() for var in ('feature', 'table')):
    print("all exist")
else:
    print("at least one not exists")

Output:

all exist

但当然,我同意@deceze,但@kaya3 证明了一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM