簡體   English   中英

Python-+不支持的操作數類型:“ int”和“ list”

[英]Python - Unsupported Operand type(s) for +: 'int' and 'list'

我試圖在列表中找到列表的平均值。 我的代碼:

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'

您需要遍歷列表,並嘗試將sum函數應用於子列表的最后4個項目:

>>> [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]

scores[3:5]從列表列表中查找一個切片。 您想要諸如scores[0][3:5]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM