Py学习  »  Python

将包含字符串和整数的列表中的元素求和,并将答案放入另一个列表python中

user8760022 • 5 年前 • 1630 次点击  

我必须写一个代码来计算列表中每个学生的成绩之和并返回总数。 我的代码是:

list=['student1',10,20,40,'student2',20,20,40,'student3',20,30,40,'student4',20,10,30]
list2=[]
for i in range(0,len(list1),4):
    list2.append(list1[i])
    for j in range(len(list1)):
        if j%4 == 1:
            sum= list1[j]+list1[j+1]+list1[j+2]
            list2.append(sum)
print(list2)

预期产出应如下:

['student1', 70, 'student2', 80,'student3', 90, 'student4', 60]

但我得到了这个结果:

['student1', 70, 80, 90, 60, 'student2', 70, 80, 90, 60, 'student3', 70, 80, 90, 60, 'student4', 70, 80, 90, 60]

​

那么我的代码怎么了?

​

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51412
 
1630 次点击  
文章 [ 6 ]  |  最新文章 5 年前