我必须编写代码以汇总列表中每个学生的成绩并返回总数。 我的代码是:
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]
那我的代码怎么了?
答案 0 :(得分:1)
在第二个循环中,您再次循环遍历整个初始列表1,因此,您总会附加所有总和。如果您的列表中确实总是包含一个名字和三个等级,那么您可以摆脱第二个循环,而只需像现在一样使用第一个循环中的“ i”作为总和的迭代器即可。
答案 1 :(得分:1)
您可以通过单循环执行此操作:
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]
答案 2 :(得分:1)
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)
产生
['student1', 70, 'student2', 80, 'student3', 90, 'student4', 60]
代码中的第二个for循环遍历列表中的每个元素,并在索引mod 4为1时采取措施。您不需要两个for循环。
答案 3 :(得分:1)
我是这样的:0、4、8,所以您不需要第二个for循环。
您已经知道数字在哪里。(i + 1,i + 2,i + 3),i是学生姓名。
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.Build());
});
答案 4 :(得分:0)
尝试
in_lst = ['student1', 10, 20, 40, 'student2', 20, 20, 40, 'student3', 20, 30, 40, 'student4', 20, 10, 30]
out_lst = []
for x in range(0, len(in_lst), 4):
student_entry = in_lst[x:x + 4]
out_lst.append(student_entry[0])
out_lst.append(sum(student_entry[1:]))
print(out_lst)
输出
['student1', 70, 'student2', 80, 'student3', 90, 'student4', 60]
答案 5 :(得分:0)
这是解决方案,您无需担心学生的否定分数。
list1=['student1',10,20,40,'student2',20,20,40,'student3',20,30,40,'student4',20,10,30]
student_name =[]
student_name_index =[]
for i in range(len(list1)):
if type(list1[i]) == int:
pass
else:
student_name.append(list1[i])
student_name_index.append(i)
student_name_index.append(len(list1)-1)
total_marks=[]
for i in range(1,len(student_name_index)):
total_marks.append(sum(list1[student_name_index[i-1]+1:student_name_index[i]]))
final_result =[]
for name, mark in zip(student_name,total_marks):
final_result.append(name)
final_result.append(mark)
print(final_result)
# output ['student1', 70, 'student2', 80, 'student3', 90, 'student4', 30]