[Python 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()
中创建的每个字典都可能以相同的顺序迭代其键。而且我不想使用 locals()
。
请注意,函数 print_table()
和 f()
还执行许多其他操作;所以我必须将它们分开。
代码应该怎么写?
最佳答案
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__
这还允许您指定哪些变量作为列,而不是在函数中临时存在。
关于python - 打印带标题的表格时替代 locals(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4067463/