所以我编写了这段代码,以便可以使用List并使用For循环来计算主题的平均成绩,但是我想知道是否还有一种方法可以使用While循环来进行相同的处理。如果可以,怎么办?
mathavg=[[3.5],[3.7],[4],[4.2],[3.6]]
m = 0
for grade1 in mathavg:
m += sum(grade1)
print("The average score for the subject of Mathematics is: ",m / len(mathavg))
非常感谢!
答案 0 :(得分:0)
没有任何理由,我能说的最好的就是模拟一个带有while循环的for循环。
mathavg=[[3.5],[3.7],[4],[4.2],[3.6]]
m = 0
i = 0
while i < len(mathavg):
m += sum(mathavg[i])
i += 1
尽管您可以使用任何一种理解方式。
m = sum([sum(i) for i in mathavg])
答案 1 :(得分:0)
您可以遍历mathavg
,在每次迭代中删除项目,直到其为空:
mathavg=[[3.5],[3.7],[4],[4.2],[3.6]]
m = 0
while mathavg:
grade = mathavg.pop()
m += sum(grade1)
print("The average score for the subject of Mathematics is: ",m / len(mathavg))
或遍历索引:
mathavg=[[3.5],[3.7],[4],[4.2],[3.6]]
m = 0
i = 0
while i < len(mathavg):
m += sum(mathavg[i])
i += 1