python - 对包含字符串和整数的列表中的元素求和,并将答案放入另一个列表 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>
解决方案
它是这样的: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)
推荐阅读
- javascript - 获取 HTML 内容下的 href 列表
- python - 有没有办法在网站上嵌入使用 python 的 Networkx 包的图形代码,以便输出可以直接显示在网站上?
- r - 利用回收将不同长度的列表转换为数据帧的功能
- node.js - 导出的函数在另一个文件 nodejs 中不起作用
- ios - 如何从函数内部获取文本字段的文本?
- .net - 使用 DebugDiag 调试挂起 - GC 挂起?
- java - 接受许可后如何运行相机
- javascript - 交替执行功能
- configuration - 如何修改默认的 graphdb.home 目录?
- javascript - 我的按钮不是由 p5js 创建的,我使用 addEventListener "click" 事件和里面的 loop(),但是当我点击那个按钮时循环运行一次