from numpy import mean
goodsInput_csv_path_name = "goodsInput.csv"
goodsTotal_csv_path_name = "goodsTotal.csv"
def save_dict_to_file(save_dict, file_path_name):
with open(file_path_name, "w") as file:
for key in save_dict:
file.write(key + ':')
for value in save_dict[key]:
file.write(str(value) + ',')
file.write('\n')
file.close()
def read_dict_to_file(file_path_name):
return_dict = {}
with open(file_path_name, "r") as file:
for line in [line for line in file.readlines() if line != ""]:
return_dict[line.split(':')[0]] = [float(line) for line in line.split(':')[1].replace('\n', '').split(',') if line != ""]
return return_dict
def goodsInputer():
goods_dict = {}
while True:
try:
inp = input("请输入商品信息(商品名称,单价,数量),直接输入回车退出:")
if inp == "":
break
else:
if inp.split(',')[0] in goods_dict:
goods_dict[inp.split(',')[0]].append(float(inp.split(',')[1]))
goods_dict[inp.split(',')[0]].append(float(inp.split(',')[2]))
else:
goods_dict[inp.split(',')[0]] = [float(inp.split(',')[1]), float(inp.split(',')[2])]
except Exception as e:
print("【错误】输入了不正确的数据格式!")
save_dict_to_file(goods_dict, goodsInput_csv_path_name)
return goods_dict
def goodsTotal():
goods_dict = read_dict_to_file(goodsInput_csv_path_name)
goods_total_dict = {}
print("各商品的平均单价和销售总数量:")
print("商品名称\t平均单价\t销售总数量")
for key in goods_dict:
goods_total_dict[key] = [0, sum([goods_dict[key][i] for i in range(1, len(goods_dict[key]), 2)])]
goods_total_dict[key][0] = sum([goods_dict[key][i] * goods_dict[key][i+1] / goods_total_dict[key][1] for i in range(0, len(goods_dict[key]), 2)])
print(key+'\t'+str(goods_total_dict[key][0])+'\t'+str(goods_total_dict[key][1]))
save_dict_to_file(goods_total_dict, goodsTotal_csv_path_name)
return goods_total_dict
def goodsFinder(goods_name):
if goods_name in read_dict_to_file(goodsInput_csv_path_name):
return goods_name
else:
return -1
def goodsSaleQtyRanker(goods_name):
goods_total_dict = read_dict_to_file(goodsTotal_csv_path_name)
return len([goods_total_dict[key] for key in goods_total_dict if goods_total_dict[key][1] > goods_total_dict[goods_name][1]]) + 1
if __name__ == '__main__':
goodsInputer()
goods_total_dict = goodsTotal()
goods_name = goodsFinder(input("请输入查询商品名称:"))
if goods_name != -1:
print(goods_name + "的销售数量是" + str(goods_total_dict[goods_name][1]) + ",在列表中排名第" + str(goodsSaleQtyRanker(goods_name)))
else:
print("没有找到此商品!")