Skip to main content
 首页 » 编程设计

python之在 Python for 循环中比较列表中的元素

2025年05月04日16arxive

代码中end方法有什么问题?

end 方法总是返回 1,尽管它应该返回带有当前数据的 0。

# return 1 if the sum of four consecutive elements equal the sum over other sum of the other three sums 
# else return 0 
# Eg the current sums "35 34 34 34" should return 0     
 
data = "2|15|14|4|12|6|7|9|8|10|11|5|13|3|2|16" 
arra = data.split("|"); 
 
def do_row ( arra, n ): 
        return arra[4*n:4 + 4*n] 
 
def row_summa (row): 
        return sum(map(int,row)) 
 
def end ( summat ):                                     # problem here! 
        equality = 1  
        for i in summat[2:5]: 
                print "Comparing: ", summat[1], " and ", i, ".\n" 
                if summat[1] != i: 
                        equality = 0  
        print equality 
 
for i in range(0,4): 
        summat = [] 
        summat.append( row_summa( do_row(arra,i) ) )  
        print row_summa ( do_row(arra,i) ) 
        summa = 0  
 
end(summat) 

请您参考如下方法:

我真的不能告诉你在这里试图做什么,但我可以肯定地说为什么 end() 返回 1 而不是 0。在你最后的 for 循环,你在循环开始时将 summat 重置为 [],所以在最后,summat 只包含一个值(你最近附加的值) .因此,当您在单个项目的列表中请求 summat[2:5] 时,Python 返回一个空列表(因为该范围内没有值)——在这种情况下,没有机会equality 设置为零,因为 end 中的循环永远不会运行。