Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - To input a file and get a formatted string output using .format()

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:

enter image description here

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:

enter image description here

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Can be solved by :

def calculate_expenses(filename):
    file_pointer = open(filename, 'r')
    # You can use either .read() or .readline() or .readlines()
    data = file_pointer.readlines()
    # NOW CONTINUE YOUR CODE FROM HERE!!!

    my_dictionary = {}
    for line in data:
        item, price= line.strip().split(',')

        my_dictionary[item.strip()] = my_dictionary.get(item.strip(),0) + float(price)
    dic={}
    for k,v in my_dictionary.items():
        dic[k]='${0:.2f}'.format(round(v,2))

    L=([(k,v) for k, v in dic.iteritems()])
    L.sort()

    return L

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...