【问题标题】:Sum of elements in nested list using for loop使用for循环嵌套列表中的元素总和
【发布时间】: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


【解决方案1】:

问题发生在

if i > 0 and i == -150:

i不能同时为正值和-150。

也许您想改用or

另外,如果你想查找索引为 -1 的元素,最好使用列表索引而不是显式使用 -150。

【讨论】:

    【解决方案2】:

    您必须更改您的 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

    【讨论】:

    • 赋值要求在总和中包含最后一个元素,无论它是正数还是负数。这里索引-1是-150。这就是为什么
    • @diyer13619,我刚刚更新了我的答案。希望对你有帮助。
    猜你喜欢
    • 2016-08-25
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 2015-02-14
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多