【发布时间】:2016-11-25 22:03:52
【问题描述】:
def main():
salesData= readData('icecream.txt')
print(salesData)
#printReport(salesData)
# Reads the tabular data
# @param filename name of the input file
# @return a dictionary whose keys are ice cream flavors and whose values are sales data.
def readData(filename):
# Create an empty dictionary.
salesData={}
infile=open(filename, "r")
# Read each record from the file.
for line in infile:
fields=line.split(":") # what is field datatype
flavor=fields[0]
salesData[flavor]=buildList(fields)
#print("SalesData", salesData)
#print()
#print()
infile.close()
return salesData
# Builds a list of store sales contained in the fields split from a string.
# @param fields a list of strings comprising the record fields
# @return a list of floating-point values
def buildList(fields):
storeSales= []
for i in range (1, len(fields)):
sales=float(fields[i])
storeSales.append(sales)
#print('StoreSales', storeSales)
#print()
return storeSales
# Prints a sales report.
def printReport(salesData):
numStores=0
#print the dictionary first without the totals?
#call print report
main()
当我以当前状态运行程序时,它会给我以下输出:
{'chocolate': [10225.25, 9025.0, 9505.0], 'strawberry': [9285.15, 8276.1, 8705.0], 'cookie dough': [7901.25, 4267.0, 7056.5], 'rocky road': [6700.1, 5012.45, 6011.0], 'vanilla': [8580.0, 7201.25, 8900.0]}
但是,我需要它看起来像这样:
chocolate 10225.25 9025.0 9505.0 Total: 28755.25
vanilla 8580.0 7201.25 8900.0 Total: 24681.25
rocky road 6700.1 5012.45 6011.0 Total: 17723.55
strawberry 9285.15 8276.1 8705.0 Total: 26266.25
cookie dough 7901.25 4267.0 7056.5 Total: 19224.75
**42691.75 33781.8 40177.5**
干净、有条理、标签式、完美对齐。我不知道如何以干净的方式从字典中提取数据。此外,我还必须添加巧克力等的总数以及第 1、第 2 和第 3 列。介绍很重要。这不仅仅是“我如何输出数据”,而是“我如何以干净的呈现方式输出数据”。我正在考虑使用嵌套的 for 循环,或者可能是带有 for 循环的东西。但是那个 for 循环的去向,或者我如何使用它来干净地打印出字典数据,我希望它看起来像什么,这超出了我的范围。我查看了其他问题,但没有什么能比得上来自字典的数据的制表、组织和打印细节。我也尝试过经常引用的“for key, val in X.items():”,但这对我没有用。我什至不知道从哪里开始该功能及其令人难以置信的混乱。我会把它放在哪里?我该如何命名它?我会从那里去哪里?更不用说我有要添加的列和要添加的行。这是一个非常具体的问题。谢谢你。
【问题讨论】:
-
我不知道那里发生了什么......
-
彼得的答案没有解决列添加问题......而且,您的代码非常出色并且效果很好,只是没有添加列。我正在考虑(也许你可以在这里帮助我)将三列(col1、col2 和 col3)初始化为 0,然后 += 它们的值 [0] [1] 和 [2] 然后打印
print("\t\t", col1, "\t", col2, "\t", col3)但是它不起作用:它不打印列的总和。只是其中一种口味。 -
是的。我从您的建议中得到了我想要的输出,并且顺利运行它;但是,它只丢失了三个数字:
42691.75 33781.8 40177.5。也就是说,我仍然不知道如何将每个键的 [0] 值相加成一个打印在相应列下方的数字(重复 [1] 值和 [2] 值)。 -
好吧@ice cream,我的分站结束了。让我知道它是否适合你。
标签: python dictionary format output