gpt4 book ai didi

Python:如何测试潜在的变量名称是否在命名空间中?

转载 作者:行者123 更新时间:2023-12-04 17:03:56 24 4
gpt4 key购买 nike

如何测试命名空间中潜在变量名称列表的哪些元素?我应该将它们初始化为 None 还是它们是更好的方法?

# Potential list. Won't work, will give NameError if one of them is not in the namespace
all_vars = [rds.rclass, \
rds.rlevel, \
rds.seg \] # the list is actually much longer

#Could do:
all_vars =[]
try:
all_vars.append(rds.rclass)
except NameError:
pass
....

#or as initially said:
rds.rclass = rds.rlevel = ... = None

还有另一种(更好)的方法吗?

最佳答案

可怕,但这应该有效:

all_vars = locals().get('all_vars', [])

关于Python:如何测试潜在的变量名称是否在命名空间中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21627812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com