打印带有标题的表时可以替代locals() [英] Alternative to locals() in printing a table with a header
问题描述
[Python 3.1]
原始代码有误.
我需要打印一张桌子.第一行应该是标题,其中包含由制表符分隔的列名称.以下各行应包含数据(也用制表符分隔).
I need to print a table. The first row should be a header, which consists of column names separated by tabs. The following rows should contain the data (also tab-separated).
为澄清起见,假设我有速度",功率",重量"列.我最初是在我之前问过的相关问题的帮助下编写的以下代码:
To clarify, let's say I have columns "speed", "power", "weight". I originally wrote the following code, with the help from a related question I asked earlier:
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()
.
But then I learned that I should avoid using locals()
if possible.
现在,我被卡住了.我不想多次键入所有列名称的列表.我不想依赖这样的事实,即我在f()
中创建的每个字典都可能以相同的顺序遍历其键.而且我不想使用locals()
.
Now I'm stuck. I don't want to type the list of all the column names more than once. I don't want to rely on the fact that every dictionary I create inside f()
is likely to iterate through its keys in the same order. And I don't want to use locals()
.
请注意,函数print_table()
和f()
还有很多其他功能;所以我必须将它们分开.
Note that the functions print_table()
and f()
do a lot of other stuff; so I have to keep them separate.
我应该如何编写代码?
推荐答案
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__
这也使您可以指定哪些变量是列,而不是在函数中是临时变量.
This also lets you specify which of the variables are meant as columns, instead of rather being temporary in the function.
这篇关于打印带有标题的表时可以替代locals()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!