可以统计省份种类,但字典值都为1
students={}
dic1={}
total=0
list1=[]
for i in range(1,11):
students["学号"]=input("请输入第{}个学生的学号\n".format(i))
students["姓名"]=input("请输入第{}个学生的姓名\n".format(i))
students["年龄"]=int(input("请输入第{}个学生的年龄\n".format(i)))
students["省份"]=input("请输入第{}个学生的省份\n".format(i))
list1.append(students)
total+=students.get("年龄",0)
key=students.get("省份")
dic1.setdefault(key,dic1.get(key,0)+1)
print("所有学生的平均年龄为{}各省份人数统计{}".format(total/10,dic1))
Python循环赋值给字典赋值出现问题,小白求讲解
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- CSDN专家-showbo 2021-09-29 13:44关注
dic1.setdefault(key,dic1.get(key,0)+1)
===>改为下面的,因为setdefault是当key不存在时才会设置内容,所以同一个省的设置过一次之后,再有同省份值也不会设置这个省份的值了
dic1[key]=dic1.get(key,0)+1而且students={}要放循环里面,要不list1添加的都是同一个对象,内容会全部一样,为最后一个录入的信息。有帮助麻烦点个采纳【本回答右上角】,谢谢~~
dic1={} total=0 list1=[] for i in range(1,11): students={}#放里面,要不 students["学号"]=input("请输入第{}个学生的学号\n".format(i)) students["姓名"]=input("请输入第{}个学生的姓名\n".format(i)) students["年龄"]=int(input("请输入第{}个学生的年龄\n".format(i))) students["省份"]=input("请输入第{}个学生的省份\n".format(i)) list1.append(students) total+=students.get("年龄",0) key=students.get("省份") dic1[key]=dic1.get(key,0)+1 print("所有学生的平均年龄为{}各省份人数统计{}".format(total/10,dic1))
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报