【发布时间】:2021-12-17 04:02:48
【问题描述】:
我是python的绝对初学者,所以请指导我哪里错了。我有一个嵌套的分数列表,我需要计算所有正整数和 [-1] 索引的总和。 我已将嵌套循环转换为平面列表,现在尝试求和,但我似乎得到的总数为 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
【问题讨论】:
-
请修正缩进,以便我们可以看到函数中有哪些行。
-
if i > 0 and i == -150:永远不可能...... -
欢迎来到 Stack Overflow!改掉使用
for index in range(len(list)):的习惯。使用for item in list: -
你为什么要把它转换成一个平面列表?
-
total == total + matrix_flatList[i]是一个错字,意味着您比较值,并且即使if测试通过,也永远不要重新分配total。=是赋值,==是相等比较。
标签: python loops nested sum iteration