打印带有标题的表格时 locals() 的替代方案

1 投票
3 回答
900 浏览
提问于 2025-04-16 06:22

[Python 3.1]

编辑:原始代码有错误。

我需要打印一个表格。第一行应该是表头,包含用制表符分隔的列名。接下来的行应该是数据(同样用制表符分隔)。

为了更清楚,假设我有三列,分别是“速度”、“功率”和“重量”。我最开始写了以下代码,参考了我之前问的一个相关问题

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

但后来我了解到,应该尽量避免使用 locals()

现在我遇到麻烦了。我不想重复输入所有列名的列表。我也不想依赖于在 f() 函数内部创建的每个字典的键是按同样的顺序遍历的。而且我不想使用 locals()

请注意,print_table()f() 这两个函数还做了很多其他的事情,所以我必须把它们分开。

我该怎么写代码呢?

3 个回答

0

一个替代 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 }
0

你可以使用一个叫做 OrderedDict 的东西来固定字典的顺序。不过我觉得其实这并不是必须的。因为你总是从 column_names 这个列表中获取键(除了最后一行,我猜那是个笔误),所以值的顺序总是会保持一致。

2
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__

这段话的意思是,你可以指定哪些变量是用作列的,而不是在函数中只是临时使用的。

撰写回答