27.文件a.txt内容:每一行内容分别为商品名字,价钱,个数。
apple 10 3
tesla 100000 1
mac 3000 2
lenovo 30000 3
chicken 10 3
通过代码,将其构建成这种数据类型:
[{'name':'apple','price':10,'amount':3},{'name':'tesla','price':1000000,'amount':1}......] 并计算出总价钱.'''
import re
lst = []
sum = 0
with open('c','r',encoding='utf-8') as f1:
lst_title = ['name','price','amount'] # 建立一个表头列表
for line in f1:
dic = {}
li = re.sub(r's{1,}',',',line).strip(',').split(',')
for i in range(len(lst_title)):
dic[lst_title[i]] = li[i]
lst.append(dic)
print(lst)
for i in lst:
print(i)
sum += int(i['price'])*int(i['amount'])
print(sum)