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

1 投票
5 回答
1754 浏览
提问于 2025-04-15 15:40

代码中的 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)

5 个回答

2

我觉得你可能犯了一个“错位一”的错误。记住,在Python中,数组的索引是从0开始的,而不是从1开始的。所以在你做这个的时候:

   for i in summat[2:5]:
            print "Comparing: ", summat[1], " and ", i, ".\n"
            if summat[1] != i:
                    equality = 0 

你根本没有查看summat[0]。你可以试试这个:

   for i in summat[1:4]:
            print "Comparing: ", summat[0], " and ", i, ".\n"
            if summat[0] != i:
                    equality = 0 
2

我不太明白你想做什么,但我可以告诉你为什么 end() 返回的是 1 而不是 0。在你最后的 for 循环中,你在循环开始时把 summat 重置为 [],所以到最后,summat 里只剩下一个值(就是你最近加进去的那个)。当你请求 summat[2:5] 时,因为 summat 里只有一个值,Python 会返回一个空列表(因为在这个范围内没有值)。这样的话,equality 就没有机会被设置为零,因为 end 里的循环根本没有执行。

1

你也应该看看这段代码

data = "2|15|14|4|12|6|7|9|8|10|11|5|13|3|2|16"
arra = map(int,data.split("|"))
summat = [sum(arra[i:i+4]) for i in range(0,len(arra),4)]
print summat
print len(set(summat))==1

撰写回答