可以统计省份种类,但字典值都为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))
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))
dic1.setdefault(key,dic1.get(key,0)+1)换成
if dic1.get(key):
dic1[key] += 1
else:
dic1[key] = 1
你这种写法只有省份不在dic1里时才会添加并设置值为1。如果已经存在,他啥也不做。值一直是1.