Python 为什么仍然给出类型错误?

Python 为什么仍然给出类型错误?,python,typeerror,magic-square,Python,Typeerror,Magic Square,我正在制作一个python程序来检查给定的值是否代表幻方 import math r1=[8,1,6] r2=[3,5,7] r3=[4,9,2] c1=zip(r1[:1],r2[:1],r3[:1]) c1= (list(c1)) c2=zip(r1[1:2],r2[1:2],r3[1:2]) c2=(list(c2)) c3=zip(r1[2:3],r2[2:3],r3[2:3]) c3= (list(c3)) print (c1,c2,c3) print(type(c1),type(c2

我正在制作一个python程序来检查给定的值是否代表幻方

import math
r1=[8,1,6]
r2=[3,5,7]
r3=[4,9,2]
c1=zip(r1[:1],r2[:1],r3[:1])
c1= (list(c1))
c2=zip(r1[1:2],r2[1:2],r3[1:2])
c2=(list(c2))
c3=zip(r1[2:3],r2[2:3],r3[2:3])
c3= (list(c3))
print (c1,c2,c3)
print(type(c1),type(c2),type(c3))
t1=math.fsum(r1)
t2=math.fsum(r2)
t3=math.fsum(r3)
t4=math.fsum(c1)
t5=math.fsum(c2)
t6=math.fsum(c3)
print(t1,t2,t3,t4,t5,t6)
if(t1==t2==t3==t4==t5==t6):
    print ("yes")
else:
    print("no")
>>> r1=[8,1,6]
>>> r2=[3,5,7]
>>> r3=[4,9,2]
>>> arr = [r1, r2, r3]
>>> row_sum = set(map(sum, arr))
>>> col_sum = set(map(sum, zip(*arr)))
>>> if len(row_sum) == 1 and row_sum == col_sum:
        print ('Magic square')
但是排队 t4=数学值fsum(c1)


虽然t4的类型仅显示列表,但它给出了类型错误

c1
变量中有元组列表:
[(8,3,4)]
。您可以通过以下方式构造
c1
(和其他内容):
c1=[r1[0],r2[0],r3[0]]

但我建议您将幻方存储在一个变量中,如:
magic=[[8,1,6],[3,5,7],[4,9,2]
。现在,您可以获得第i行元素的总和,即
sum(magic[i])
,对于列,请尝试列表理解:

sum([magic[i][j] for i in range(3)])

其中j-列数。

正如已经建议的那样,zip返回一个元组,并将其作为列表,只将相同的元组放入列表中。但是,下面的代码将执行您想要的操作

import math
r1=[8,1,6]
r2=[3,5,7]
r3=[4,9,2]
c1=r1[:1]+r2[:1]+r3[:1]
#c1= list(c1)
c2=r1[1:2]+r2[1:2]+r3[1:2]
#c2=(list(c2))
c3=r1[2:3]+r2[2:3]+r3[2:3]
#c3= (list(c3))
print (c1,c2,c3)
print(type(c1),type(c2),type(c3))
t1=math.fsum(r1)
t2=math.fsum(r2)
t3=math.fsum(r3)
t4=math.fsum(c1)
t5=math.fsum(c2)
t6=math.fsum(c3)
print(t1,t2,t3,t4,t5,t6)
if(t1==t2==t3==t4==t5==t6):
    print ("yes")
else:
    print("no")
输出将是:

[8, 3, 4] [1, 5, 9] [6, 7, 2]
<class 'list'> <class 'list'> <class 'list'>
15.0 15.0 15.0 15.0 15.0 15.0
yes
[8,3,4][1,5,9][6,7,2]
15.0 15.0 15.0 15.0 15.0 15.0
对

将一个列表中的所有行存储为列表列表。检查该列表所表示的数组是否为幻方会更容易

import math
r1=[8,1,6]
r2=[3,5,7]
r3=[4,9,2]
c1=zip(r1[:1],r2[:1],r3[:1])
c1= (list(c1))
c2=zip(r1[1:2],r2[1:2],r3[1:2])
c2=(list(c2))
c3=zip(r1[2:3],r2[2:3],r3[2:3])
c3= (list(c3))
print (c1,c2,c3)
print(type(c1),type(c2),type(c3))
t1=math.fsum(r1)
t2=math.fsum(r2)
t3=math.fsum(r3)
t4=math.fsum(c1)
t5=math.fsum(c2)
t6=math.fsum(c3)
print(t1,t2,t3,t4,t5,t6)
if(t1==t2==t3==t4==t5==t6):
    print ("yes")
else:
    print("no")
>>> r1=[8,1,6]
>>> r2=[3,5,7]
>>> r3=[4,9,2]
>>> arr = [r1, r2, r3]
>>> row_sum = set(map(sum, arr))
>>> col_sum = set(map(sum, zip(*arr)))
>>> if len(row_sum) == 1 and row_sum == col_sum:
        print ('Magic square')

c1
是一个包含元组的列表
fsum
需要的是一个数字序列,而不是一个元组序列。@khelwood我如何将这个元组转换为列表,或者如何避免列出元组请参见下面的答案。如果您想坚持您的解决方案但消除错误,这是一个备选方案:
c1,c2,c3=np。重塑((r1+r2+r3),(3,3)).T
Rest保持不变。