【发布时间】:2021-06-18 08:58:17
【问题描述】:
我正在尝试读取此文本文件并显示其数据。我应该报告产品名称、价值和最有价值的产品。我在最后添加了到目前为止我尝试过的事情:
Here is how the text file looks like:
item name 1 ex: hats
quantity of item 1 ex: 12
unit price of item 1 ex: 5.9
item name 2 ex: jacket
quantity of item 2 ex: 13
unit price of item 2 ex: 29.9
Expected output
12 hats at 5.9 the unit. total value: 70.8
13 jackets at 29.9 the unit. total value: 390
total inventory value: 460.8
most valuable inventory: jacket: 390
到目前为止我尝试过的事情:
filename = "store.txt"
with open(filename) as f:
content = f.read().splitlines()
content_list = [content[i * 3:(i + 1) * 3] for i in range((len(content) + 3 - 1) // 3)]
total_value = 0
for items in content_list:
value = float(items[2])*(float(items[1]))
print(items[1],'', items[0], '@ $', items[2], '. Value: $', value)
total_value += value
#max_value = max(value)
print('')
print('total value: '+ str(total_value))
#print('Highest value item: ' + str(max_value))
【问题讨论】:
-
请展示您的尝试
-
是的,我的错,我将编辑并添加我尝试过的内容。
-
我刚刚添加了新的编辑
-
更多
pyhonic(更好的做法)被认为是使用with而不是open和close,因为with语句会自动关闭从而避免潜在的错误。