gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:12:10 24 4
gpt4 key购买 nike

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

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]

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

最佳答案

你可以用一个循环来完成:

lst = ['student1', 10, 20, 40, 'student2', 20, 20, 40, 'student3', 20, 30, 40, 'student4', 20, 10, 30]
result = []
for i in range(0, len(lst), 4):
result.extend((lst[i], sum(lst[i+1:i+4])))

输出:

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

如果每个学生的分数不同,例如:

lst = ['student1', 10, 20, 'student2', 10, 20, 30, 'student3', 10, 20, 30, 40, 'student4', 10, 20, 30, 40, 50]

然后:

s = 0
result = [lst[0]]
for i in lst[1:]:
try:
s += int(i)
except ValueError:
result.extend((s, i))
s = 0
result.append(s)

输出:

['student1', 30, 'student2', 60, 'student3', 100, 'student4', 150]

关于python - 对包含字符串和整数的列表中的元素求和,并将答案放入另一个列表 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55181008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com