我有一个像这样的文本文件:
month /name/ number/ price
1 John 100 120.00
1 Sean 90 125.00
1 Laura 150 100.00
1 Joseph 95 140.00
1 Pam 91 105.00
2 John 110 120.00
2 Sean 98 100.00
2 Laura 100 100.00
2 Joseph 89 150.00
2 Pam 100 100.00
3 John 100 121.00
3 Sean 90 120.00
3 Laura 97 100.00
3 Joseph 120 110.00
3 Pam 101 100.00
我需要获得特定人(例如Pam)每月的收入以及1,2和3个月内的总收入(数字*价格)。我在下面的代码和下面的输出。但是我不知道如何获得总收入,有人可以给我一些建议或想法吗?
#This is the code I use
f = input('Enter The File Name:')
sales_data = open("sales.txt",'r')
lines = sales_data.readlines()
m = input('Enter the Manager Name:')
print('Monthly Sales Report for' +' ' + m)
for line in lines:
line = line.split()
tr = (float(line[2]) * float(line[3]))
if m in line:
print(line[0] +' ' + line[2] + ' ' + line[3] +' ' + str(tr))
#This is the output I got
Enter the Manager Name: Pam
Monthly Sales Report for Pam
1 91 105.00 9555.0
2 100 100.00 10000.0
3 101 100.00 10100.0
解决问题的一种可能方法是将所有月度值存储在特定经理的字典中:
file_name = input('Enter The File Name: ')
manager_summary = {'1':0.0, '2':0.0, '3':0.0}
with open (file_name, 'r') as fin:
lines = fin.readlines()
manager = input('Enter the Manager Name: ')
print('Monthly Sales Report for' +' ' + manager)
for line in lines:
line = line.split()
if manager in line:
manager_summary[line[0]] += float(line[-2])*float(line[-1])
manager_total = 0.0
for key, value in manager_summary.items():
manager_total += value
print(manager_total)
该代码立即读取输入文件,在所有行中循环搜索目标经理,并将该经理的累积每月销售额存储在字典中。然后,通过将字典中存储的每个月的累计值相加来计算三个月期间的总收入。
关于您的原始代码,有几处更改值得注意:
open
此代码打开文件with open
-使用open是上下文管理器,它将在需要关闭时自动为您关闭文件,这是程序中缺少的内容。f
,m
这样的变量,它会使程序更易于出错,并且可读性更差。这里使用的是冗长的,您总是可以在两者之间提出一些建议。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句