首页 > 解决方案 > 对包含字符串和整数的列表中的元素求和,并将答案放入另一个列表 python

问题描述

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

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]

​</p>

那么我的代码有什么问题?

​</p>

标签: pythonpython-3.xlistsumjupyter-notebook

解决方案


它是这样的:0、4、8,所以你不需要第二个 for 循环。

你已经知道数字在哪里了。(i+1,i+2,i+3) 我是学生的名字。

list1=['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])
    sum = list1[i+1]+list1[i+2]+list1[i+3]
    list2.append(sum)
print(list2)

推荐阅读