Write a function named calculate_expenses
that receives a filename as argument. The file contains the information about a person's expenses on items. Your function should return a list of tuples sorted based on the name of the items. Each tuple consists of the name of the item and total expense of that item as shown below:
Notice that each line of the file only includes an item and the purchase price of that item separated by a comma. There may be spaces before or after the item or the price. Then your function should read the file and return a list of tuples such as:
Notes:
Tuples are sorted based on the item names i.e. bread comes before chips which comes before milk.
The total expenses are strings which start with a $ and they have two digits of accuracy after the decimal point.
Hint: Use ${:.2f}
to properly create and format strings for the total expenses.
The code so far:
def calculate_expenses(file_name):
file_pointer = open(file_name, 'r')
data = file_pointer.readlines()
list_main=[]
for line in data:
name, price = line.strip().split(',')
print (name, price)
Output:
('milk', '2.35')
('bread ', ' 1.95')
('chips ', ' 2.54')
('milk ', ' 2.38')
('milk', '2.31')
('bread', ' 1.90')
I can't get rid of the spaces and don't know what to do next.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…