int类型的对象不可迭代

时间:2015-06-02 20:59:48

标签: python int iteration

这是我的代码:

NUM = 3                
A = [1,5,6,2,8,4,3,2,5]
B = []
m = []
check = False
summ=0
n = len(A) / NUM
while check == False: 
    for i in A:
        if A.index(i) >= n:
            B.append(m)
            m = []
            n *= 2
        m.append(i)
    B.append(m)
    for j in B:
        s1=(sum(B[0]))
        s2=(sum(B[1]))
        s3=(sum(B[2]))
    print(B)
    if s1==s2==s3:
        summ=s1
        check = True
    else:
        B = [0] * len(A)
        ilg = len(A)
        B[0]=A[ilg-1]
        for i in range(len(A)-1):
            B[i+1] = A[i]
        for i in range(len(A)):
            A[i]=B[i]

我要做的是将我的列表拆分为3个列表,如果这些列表中的数字总和相等,则打印总和,如果不打印,则为“假”'。 例如:[1,2,3,4,5,6,7,8,9], 拆分后:[1,2,3],[4,5,6],[7,8,9] 但我收到一个错误: s1=[sum(B[0])] TypeError: 'int' object is not iterable 我做错了什么?

编辑:这里我有更多,其他部分应该从[1,5,6,2,8,4,3,2,5]到[5,1,5,6,2, 8,4,3,2]等等。

3 个答案:

答案 0 :(得分:0)

你的问题就在这一行:

protected function buildFailedValidationResponse(Request $request, array $errors) 
{ 
    if (/*$request->ajax() ||*/ $request->wantsJson()) { return new JsonResponse($errors, 422); 
}

您正在为B[0]=A[ilg-1] 分配一个整数,该整数不是可迭代对象。在循环的第二次迭代中,将B[0]传递给B[0]函数,该函数尝试迭代它,抛出异常。

答案 1 :(得分:0)

A = [1,5,6,2,8,4,3,2,5]
NUM = 3
n = len(A) / NUM
# here make sure that len(A) is a multiple of NUM
sums = [sum([item for item in A[i * NUM :(i + 1) * NUM]]) for i in range(n)]
# for python versions older than 3 use xrange instead of range.
for i in sums[1:]:
    if i != sums[0]:
        print "FALSE"
        break
else:
    print sums[0]

答案 2 :(得分:-1)

因为您错误地定义了范围。您希望i成为您的索引,对吗?所以使用:

for i in np.arange(0, len(B)):
导入numpy

import numpy as np

编辑:实际上不需要包,只需:for i in range(0, len(B)):