如何在Google App Engine数据存储中存储多维数组

3
class Matrix(db.Model):
 values = db.ListProperty()

obj = Matrix()

wx = [[1,0],[0,1]]

obj.put()

如何将wx矩阵存储在数据存储中?
1个回答

5
你需要对矩阵进行序列化。如何序列化数据取决于你是否要基于矩阵中的数据进行查询。
如果不需要查询,只需使用JSON(或类似的格式)。
from django.utils import simplejson as json

class Matrix(db.Model):
 values = db.StringProperty(indexed=False)

matrix = Matrix()
# will be a string like: '[[1, 0], [0, 1]]'
matrix.values = json.dumps([[1,0],[0,1]])
matrix.put()

# To get back to the matrix:
matrix_values = json.loads(matrix.values)

如果您要尝试查询包含“精确行”的矩阵,则可能需要执行以下操作:
class Matrix(db.Model):
 values = db.ListProperty()

matrix = Matrix()
values = [[1,0],[0,1]]
# will be a list of strings like:  ['1:0', '0:1']
matrix.values = [':'.join([str(col) for col in row]) for row in values]
matrix.put()

# To get back to the matrix:
matrix_values = [[int(col) for col in row.split(':')] for row in matrix.values]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接