一:文件a1.txt内容(升级题)
name:apple price:10 amount:3 year:2012
name:tesla price:100000 amount:1 year:2013
.......
通过代码,将其构建成这种数据类型:
[{'name':'apple','price':10,'amount':3},
{'name':'tesla','price':1000000,'amount':1}......]
并计算出总价钱。
1 l=[] #第一次以空格切割放数据 2 n=[] #第二次以:切割存放数据 3 lst={} #按要求格式放数据的地方 4 con=[] #最后放数据的地方 5 sum =0 6 with open('al.txt','r',encoding='utf-8') as f : 7 for line in f: #一行一行的显示 8 l=line.strip().split(' ') #去两端的空白在以空格切割 9 for i in l : #此循环将第二次以:切割 10 n=i.split(":") 11 lst[n[0]] =n[1] 12 if n[0] == 'price' : 13 sum = sum + int(n[1]) 14 con.append(lst) 15 print(con) 16 print(sum)
二:文件a2.txt内容(升级题)
序号 部门 人数 平均年龄 备注
1 python 30 26 单身狗
2 Linux 26 30 没对象
3 运营部 20 24 女生多
.......
通过代码,将其构建成这种数据类型:
[{'序号':'1','部门':Python,'人数':30,'平均年龄':26,'备注':'单身狗'},
......]
1 lst= [] 2 ls =[] 3 f = open('a2.txt','r',encoding='utf-8') 4 con = f.readline().strip().split() 5 for line in f: 6 dic = {} 7 ls = line.strip().split() 8 for n in range(len(ls)): 9 dic [con[n]] = ls[n] 10 lst.append(dic) 11 print(lst) 12 f.close()