要求:
下载文件地址:http://cdn1.python3.vip/files/py/prac_py_0016_1.zip
这里面有3列数据,分别 保存了 游戏系统的用户名, 用户积分 , 年龄
现在要求大家写一个程序,计算出同一姓氏的人的积分总和。
输出结果格式如下:
薛 : 19142
王 : 18514
尤 : 11229
贾 : 21677
学习思路+伪代码:
1 打开文件读取字符串 open()
2 按行读取(按钮换行符切割),返回结果是一个列表 read().splitlines()
3 遍历循环取出元素 for
3.1 去除左右空格 ===拿到的结果:字符串
3.2 判断空行 ===拿到的结果:字符串
# 接下来将字符串 转换成 列表
3.3 split切割,得到一个个列表
4 取出列表中name[0]-姓 判断是否存在
如果不存在就加入字典中,
如果存在修改,追加coin值字典中
5 最后一步就遍历循环字典
# 1.打开文件读取字符串
with open('0016_1.txt',encoding='utf8') as f:
# 2.按行读取,返回的是一个列表
infoList = f.read().splitlines()
# print(infoList)
dic = {}
# list中循环取出元素
for info in infoList:
# 3.去除左右空格
info = info.strip()
# 3.判断空行
if not info:
continue
# 4.split切割,得到一个个列表
infoSplit = info.split(' ')
# print(infoSplit)
name = infoSplit[0]
coin = int(infoSplit[-2])
# 5.拿到name[0] 判断是否存在
if name[0] not in dic:
# 将name作为key 分数作为value
dic[name[0]] = coin
else:
dic[name[0]] += coin
# 遍历字典打印结果
for k,v in dic.items():
print(f'{k},{v}')