math=[('xiaoming',6),('xiaohong',3)]
english=[('xiaoming',3),('xiaozhang',3)]
chinese=[('xiaohong',2),('xiaozhang',4)]
score=[math,english,chinese]
total_score=[('xiaoming',9),('xiaohong',5),('xiaozhang',7)]
my_total_score=[]
for i in score:
for j in i:
if len(my_total_score)>0:
now_name,now_score=j
my_total_score_name=[i[0] for i in my_total_score]
if now_name not in my_total_score_name:
my_total_score.append(j)
else:
for i in range(len(my_total_score)):
name_score=my_total_score[i]
this_name,this_score=name_score
if now_name==this_name:
my_total_score[i]=(this_name,this_score+now_score)
if len(my_total_score)==0:
my_total_score.append(j)
print(my_total_score)
print(my_total_score==total_score)
math,english,chinese里面是每个学生的成绩,score里面保存了每个学生的成绩,需要合并计算每个学生的总的成绩,保存到total_score里面,用这么一个简单的循环去实现,完全没有问题,不知道为什么在其他机器上用pycharm会出现问题?有可能是哪行代码写错了。这个实际上用字典去解决反而更加方便。
注:python并非完美语言,尽可能使用简单的语法,大家用的最多的,反而不容易出错。
咨询问题请扫码: