我是 python 的絕對初學者,所以請指導我哪里出錯了。我有一個嵌套的分數串列,我需要計算所有正整數和 [-1] 索引的總和。我已將嵌套回圈轉換為 flatlist,現在嘗試求和,但我似乎將總數設為 0。答案應該是 3150。
你能告訴我我錯在哪里嗎?
#Create a 2D matrix with scores
#matrix (Column, Row) is a list of lists
matrix = [[0,-1000,0,0,0], [0,0,150,0,-1000], [0,-1000,1000,-1000,0], [-1000,1000,-1000,-150,0], [1000,150,0,0,-150]]
#convert nested list into flatlist
matrix_flatList = [ item for elem in matrix for item in elem]
print(matrix_flatList)
def dream_score(matrix_flatlist):
"""
A function that returns the max possible score
"""
total = 0
#Iterate each positive element in list and add them in variable total
n = len(matrix_flatList)
for i in range(0,n):
if i > 0 and i == -150:
total == total matrix_flatList[i]
#printing dream score
print("Dream score is: ", total)
#make sure to get the last variable in total even if its negative
#return final score
uj5u.com熱心網友回復:
問題發生在
if i > 0 and i == -150:
i 不能同時為正值和 -150。
也許你想or改用。
此外,如果您想查找索引為 -1 的元素,最好使用串列索引而不是顯式使用 -150。
uj5u.com熱心網友回復:
您必須更改 for 回圈才能獲得確切的輸出。
#n = len(matrix_flatList)
for i in matrix_flatList:
if i > 0:
total = total i
#to add the last element of matrix_flatList in total
total = total matrix_flatList[-1]
#printing dream score
print("Dream score is:", total)
輸出: Dream score is: 3150
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/348977.html
