Python - +:' int'不支持的操作数类型和'列出'

时间:2015-03-15 18:00:46

标签: python

我试图找到列表中列表的平均值。 我的代码:

Scores=[['James','Q',3,4,1,5],['Kat','L',3,4,1,2],['Maddy','G',3,5,6,4],['John','K',3,7,6,8],['Filip','NJ',3,8,9,9]]
size=len(Scores[3:5])
total=sum(Scores[3:5])
meanAverage=total/size
print(meanAverage)

我得到的错误是:

    total=sum(Scores[3:5])
TypeError: unsupported operand type(s) for +: 'int' and 'list'

2 个答案:

答案 0 :(得分:3)

您需要遍历列表,并尝试在最后4项子列表中应用sum函数:

>>> [sum(i[3:5])/4 for i in Scores]
[1.25, 1.25, 2.75, 3.25, 4.25]

但请注意,如果您想获得所需的数字[2:6]切片:

>>> [(i[2:6]) for i in Scores]
[[3, 4, 1, 5], [3, 4, 1, 2], [3, 5, 6, 4], [3, 7, 6, 8], [3, 8, 9, 9]]
>>> [sum(i[2:6])/4 for i in Scores]
[3.25, 2.5, 4.5, 6.0, 7.25]

答案 1 :(得分:1)

scores[3:5]正在从列表列表中查找切片。你需要像scores[0][3:5]这样的东西。