我正在为脚本的调试模式编写一些打印输出。是否有一种紧凑的方法在符合条件的列表中打印这些变量的名称?
specification_aw3 = 43534
specification_hg7 = 75445
specification_rt5 = 0
specification_nj8 = 5778
specification_lo4 = 34
specification_ee2 = 8785
specification_ma2 = 67
specification_pw1 = 1234
specification_mu6 = 0
specification_xu8 = 12465
specifications = [
specification_aw3,
specification_hg7,
specification_rt5,
specification_nj8,
specification_lo4,
specification_ee2,
specification_ma2,
specification_pw1,
specification_mu6,
specification_xu8
]
if any(specification == 0 for specification in specifications):
# magic code to print variables' names
# e.g. "variables equal to 0: \"specification_rt5\", \"specification_mu6\"
就像9000 mysqlclient repo一样,不言而喻,定义字典对于我在这里定义的最小工作示例来说是一种理性的方法。请假设这不是现有代码项目的可行选项,而且我正在寻找一个快速,紧凑(似乎难看)的代码,仅用于调试。
编辑:类似于我想要的东西的插图
所以,这是我正在寻找的开始:
print("specifications equal to zero:")
callers_local_objects = inspect.currentframe().f_back.f_locals.items()
for specification in [specification for specification in specifications if specification == 0]:
print([object_name for object_name, object_instance in callers_local_objects if object_instance is specification][0])
基本上,是否有一种紧凑的方式来做这样的事情?
答案 0 :(得分:12)
我建议您使用dict而不是一堆变量:
specification = {
'aw3': 0,
'foo': 1,
'bar': 1.23,
# etc
}
您可以按specification['aw3']
等名称访问内容。
然后您可以找到值为0
的名称:
zeroed = [name for (name, value) in specification.items() if value == 0]
答案 1 :(得分:1)
此外,由于您提到打印该行将是:
for element in specification_dictionary:
print(element)
您可以将其与上面的列表推导相结合,仅打印符合您个案的元素。如果您希望键和值都将其设置为使用specification_dictionary.items(),则此情况下的元素仅打印变量名称(键)。欢呼声。
>>> specification = { 'aw3': 0, 'foo': 1}
>>> for element in specification:
... print(element)
...
foo
aw3
>>> for (key, value) in specification.items():
... print(str(key) + " " + str(value))
...
foo 1
aw3 0
>>> for element in specification.items():
... print(element)
...
('foo', 1)
('aw3', 0)