参考这篇文章的代码封装了一个类似Matlab中的magic函数,用来生成魔方矩阵. #!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np def magic(n): row,col=0,n//2 magic=[] for i in range(n): magic.append([0]*n) magic[row][col]=1 for i in range(2,n*n+1): r,l=(row-1+n)%n,(col+1)