代码之家  ›  专栏  ›  技术社区  ›  max

在打印带有页眉的表时使用locals()的替代方法

  •  1
  • max  · 技术社区  · 14 年前

    [巨蟒3.1]

    我需要打印一张桌子。第一行应该是一个页眉,由用制表符分隔的列名组成。以下行应包含数据(也用制表符分隔)。

    为了澄清,假设我有“速度”、“力量”、“重量”栏。我最初在 related question

    column_names = ['speed', 'power', 'weight']
    
    def f(row_number):
      # some calculations here to populate variables speed, power, weight
      # e.g., power = retrieve_avg_power(row_number) * 2.5
      # e.g., speed = math.sqrt(power) / 2
      # etc.
      locals_ = locals()
      return {x : locals_[x] for x in column_names}
    
    def print_table(rows):
      print(*column_names, sep = '\t')
      for row_number in range(rows):
        row = f(row_number)
        print(*[row[x] for x in component_names], sep = '\t')
    

    但后来我知道我应该 avoid using locals() if possible .

    现在我被困住了。我不想多次键入所有列名的列表。我不想相信我在里面编的每一本字典 f() 可能以相同的顺序遍历其键。我不想用 局部变量() .

    print_table() f()

    我该怎么写代码?

    3 回复  |  直到 7 年前
        1
  •  2
  •   Martin v. Löwis    14 年前
    class Columns:
        pass
    
    def f(row_number):
        c = Columns()
        c.power = retrieve_avg_power(row_number) * 2.5
        c.speed = math.sqrt(power) / 2
        return c.__dict__
    

    这还允许您指定哪些变量表示为列,而不是函数中的临时变量。

        2
  •  0
  •   Björn Pollex    14 年前

    你可以用一个 OrderedDict 修正字典的顺序。但在我看来,这甚至是不必要的。你总是从 column_names list(除了最后一行,我认为这是一个输入错误),因此值的顺序将始终相同。

        3
  •  0
  •   mouad    14 年前

    locals()的另一种方法是使用 inspect 模块

    import inspect
    
    def f(row_number):
        # some calculations here to populate variables speed, power, weight
        # e.g., power = retrieve_avg_power(row_number) * 2.5
        # e.g., speed = math.sqrt(power) / 2
        # etc.
        locals_ = inspect.currentframe().f_locals
        return {x : locals_[x] for x in column_names }