【发布时间】:2020-06-28 18:20:15
【问题描述】:
所以我需要我的输出看起来像这样: output
最后一个问题是: 如何将每列的值添加到行字符串?
我正在定义一个函数来格式化行的打印方式,它看起来像这样:
def line_string(row_title, row_data, data_type):
row_title = f"{row_title:38}"
row_string = row_title
columns = years[-1]
for column in range(columns+1):
# Concatenate row_string per the data_type function arugment as per below
# Make each of the data columns 9 characters wide
# If data_type equals "decimal", then format as decimal with the specified width
if data_type == "integer":
row_string = row_string + f"{row_data[column]:9,}"
elif data_type == "decimal":
row_string = row_string + f"{row_data[column]:9,.2f}"
elif data_type == "percent":
row_string = row_string + f"{row_data[column]:9,.2%}"
return row_string
# this is a test:
line_string("Cumulative sum", cumulatitve_sum, "decimal")
我得到了这个错误:
TypeError Traceback (most recent call last)
in
44 return row_string
45
---> 46 line_string("Cumulative sum", cumulatitve_sum, "decimal")
in line_string(row_title, row_data, data_type)
35 elif data_type == "decimal":
---> 36 row_string = row_string + f"{row_data[column]:9,.2f}"
37
TypeError: 'function' object is not subscriptable
如何将每列的值添加到行字符串中?
【问题讨论】:
-
"Subscripting" 表示用
[]访问,所以错误指向row_data[column]。您作为row_data传递的cumulatitve_sum(顺便说一句,拼写错误)的值是多少? -
也许你的意思只是
line_string("Cumulative sum", cumulatitve_sum(), "decimal") -
也许你的意思是
f"{row_data(column):9,.2f}?cumulatitve_sum是一个函数,因此它只能接受带有()的参数,不能接受[]的参数。 -
除非绝对必要,否则请不要将信息共享为图像。请参阅:meta.stackoverflow.com/questions/303812/…、idownvotedbecau.se/imageofcode、idownvotedbecau.se/imageofanexception。
标签: python function iteration concatenation string-concatenation