您可以将customerList(作为字符串)直接传递给如下计算价格的函数。
[['potato', 'X', '8'], ['orange', 'X', '7'], ['rice', 'X', '13'], ['bread', 'X', '13']]
计算值的函数:
def calc_purchase_value(customerList_contents, price_list):
" Compute purchase value "
# convert customerList_contents to a list of list
purchase_list = [x.split() for x in customerList_contents.split('\n') if x.strip()]
# Iterate through the purchase_list looking up items in the price list
# Each sublist will be of the form [item, 'X', cnt]
return sum([price_list.get(item, 0) * int(cnt) for item, x, cnt in purchase_list])
使用自定义列表内容(将从文件中读取不同的字符串)
customerList_contents = """
potato X 8
orange X 7
rice X 13
bread X 13
"""
price_list = {"rice": 2.10,
"potato":4.21,
"orange":3.31,
"eggs":1.92,
"cheese":8.10,
"chicken":5.22}
print(calc_purchase_value(purchase_list, price_list))
#>> 84.15
完全解决方案
import glob
import os
import json
def readShopping():
" Reads each customer shopping list, returning result as a geneerator "
for file in glob.glob('./shoppinglists/*.txt'):
with open(file,'r') as customerList:
contents = customerList.read()
# return file path and contents
yield file, contents
def calc_purchase_value(customerList_contents, price_list):
" Compute purchase value "
# convert customerList_contents to a list of list
purchase_list = [x.split() for x in customerList_contents.split('\n') if x.strip()]
# Iterate through the purchase_list looking up items in the price list
# Each sublist will be of the form [item, 'X', cnt]
return sum([price_list.get(item, 0) * int(cnt) for item, x, cnt in purchase_list])
def get_prices():
" Reads prices from JSON file "
with open('./shoppinglists/pricelist.json') as json_file:
return json.load(json_file)
# - Get prices from JSON file
price_list = get_prices()
for file, contents in readShopping():
# file - path to customer file
# contents - contents of customer file
# Extract customer name from file path
basename = os.path.basename(file)
customer_name = os.path.splitext(basename)[0]
# Total price: based upon shopping list and price list
total_price = calc_purchase_value(contents, price_list)
# Show results
print('Customer {} total is: {:.2f}'.format(customer_name, total_price))
在上面,我有两个文本文件在文件夹购物列表“Mary.txt”和“James.txt”(你会说50或更多)。
Mary.txt的内容
orange X 3
rice X 2
potato X 3
eggs X 2
potato X 8
orange X 7
rice X 13
bread X 13
Customer james total is: 84.15
Customer mary total is: 30.60