我正在为脚本的调试模式编写一些打印输出。有没有一种简洁的方法来打印满足条件的列表中这些变量的名称?
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\"
正如9000suggests一样,不用说定义字典是我在这里定义的最小工作示例的一种合理方法。请假设这不是现有代码项目的可行选项,我正在寻找一种快速、紧凑(貌似丑陋)的代码,只用于调试。
编辑:类似于我想要的东西的插图
下面是我要找的开始:
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])
基本上,有没有一种紧凑的方法来做这样的事情?
最佳答案
我建议你用一个dict代替一堆变量:
specification = {
'aw3': 0,
'foo': 1,
'bar': 1.23,
# etc
}
您可以按名称访问,如
specification['aw3']
。然后您可以找到值为
0
的名称:zeroed = [name for (name, value) in specification.items() if value == 0]
关于python - 在Python中,是否存在一种紧凑的方式来在满足条件的列表中打印这些变量的名称?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42140283/