【问题标题】:In Python, is there a compact way to print the names of those variables in a list that meet a condition?在 Python 中,是否有一种紧凑的方法可以在满足条件的列表中打印这些变量的名称?
【发布时间】:2017-02-09 15:12:21
【问题描述】:

我正在为脚本的调试模式编写一些打印输出。有没有一种简洁的方法来打印列表中满足条件的那些变量的名称?

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 suggests 一样,不用说定义字典是我在这里定义的最小工作示例的合理方法。请假设这对于现有代码项目来说不是一个可行的选择,并且我正在寻找一种快速、紧凑(可能很难看)的代码,仅用于调试。


编辑:类似于我想要的东西的插图

所以这是我正在寻找的开始:

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])

基本上,有没有一种紧凑的方法来做这样的事情?

【问题讨论】:

  • 你应该使用字典。
  • 变量名不应包含数据。如果你不能在任何地方用asflaskjflasjflsajfls 替换specification_xu8,那么你做错了。
  • 那个列表在哪里?
  • @JoshLee 是的,在我给出的最小工作示例中,字典是合理的。在这种情况下,我对访问变量名的紧凑(可能是丑陋的)方式感兴趣。

标签: python list list-comprehension variable-names


【解决方案1】:

我建议你使用字典而不是一堆变量:

specification = {
  'aw3': 0,
  'foo': 1,
  'bar': 1.23,
  # etc
} 

您可以按名称访问内容,例如specification['aw3']

然后你可以找出值为0的名字:

zeroed = [name for (name, value) in specification.items() if value == 0]

【讨论】:

    【解决方案2】:

    此外,由于您提到打印该行将是:

    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)
    

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      • 2021-05-17
      • 2022-01-02
      • 2021-11-21
      • 2019-08-15
      • 1970-01-01
      相关资源
      最近更新 更多