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

Sam*_*Sam 3 google-app-engine google-cloud-datastore

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

obj = Matrix()

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

obj.put()
Run Code Online (Sandbox Code Playgroud)

如何在数据存储区内存储wx矩阵?

Rob*_*uin 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)
Run Code Online (Sandbox Code Playgroud)

如果您要尝试查询包含"确切行"的矩阵,那么您可能希望执行以下操作:

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]
Run Code Online (Sandbox Code Playgroud)