在2D列表中添加列表

时间:2016-01-06 10:25:23

标签: python list

marks = [[12,14,8,7,17],[6,8,5,3,13],[16,15,9,10,18]]

total = 0
for s in range(3):
    for m in range(5):
        total[s] = total[s] + marks [s][m]
        print("total for student",s,"is",total[s])

为什么会抛出以下错误?

TypeError: 'int' object is not subscriptable

2 个答案:

答案 0 :(得分:2)

我们可以简化您的代码并使其正常工作

<强>代码:

//a[starts-with(@href,'https://yahoo.com/us')] 

<强>输出:

marks = [[12,14,8,7,17],[6,8,5,3,13],[16,15,9,10,18]]    
total = 0
for s in range(len(marks)):
    print("total for student",s,"is",sum(marks[s]))

更改代码

<强>代码1:

total for student 0 is 58
total for student 1 is 35
total for student 2 is 68

备注:

  • 由于您尝试计算列表的总和,因此可以使用marks = [[12,14,8,7,17],[6,8,5,3,13],[16,15,9,10,18]] for s in range(3): total = 0 for m in range(5): total += marks [s][m] print("total for student",s,"is",total) 方法

答案 1 :(得分:0)

如果你要完成它,你根本不需要知道列表的长度。如果您要进行索引编制,请改用enumerate

而且,正如The6thSense所说,用sum计算每个学生的名单

提示:使用format可让您的代码更优雅! : - )

marks = [[12,14,8,7,17],[6,8,5,3,13],[16,15,9,10,18]]

for index, student in enumerate(marks):
    print('Total for student {student} is {total}'.format(student=i, total=sum(j)))

Total for student 0 is 58
Total for student 1 is 35
Total for student 2 is 68