将矩阵添加到列表
Add matrices to a list
我有这段代码可以生成一些随机矩阵:
for i in range(5):
c = randint(1,10)
r = randint(1,10)
(Matrix(QQ,[[randint(-5,5) for x in range(c)] for y in range(r)]))
我的问题是如何将这些矩阵添加到列表中?谢谢。
可以将事物添加到列表中
使用列表的 append
和 extend
方法。
示例:创建一个空列表并追加矩阵
在构建它们时使用它。
matrices = []
for _ in range(5):
c = randint(1, 10)
r = randint(1, 10)
m = Matrix(QQ, [[randint(-5, 5) for _ in range(c)] for _ in range(r)]))
matrices.append(m)
要直接构建列表,请使用 Python 的理解语法:
matrices = [
Matrix(QQ, [[randint(-5, 5) for _ in range(randint(1, 10))]
for _ in range(randint(1, 10))]))
for _ in range(5)
]
可以定义一个随机矩阵函数,
并用它来构建矩阵列表。
def my_random_matrix(emax=5, rmax=10, cmax=10):
r"""
Return a random matrix of random size.
The number of rows is picked at random between ``1`` and ``rmax``.
The number of columns is picked at random between ``1`` and ``cmax``.
The entries are integers picked at random between ``-emax`` and ``emax``.
The matrix is returned as a matrix over ``QQ``.
"""
r, c = randint(1, rmax), randint(1, cmax)
return Matrix(QQ, r, c, [randint(-emax, emax) for _ in range(r * c)])
matrices = [my_random_matrix() for _ in range(5)]
我有这段代码可以生成一些随机矩阵:
for i in range(5):
c = randint(1,10)
r = randint(1,10)
(Matrix(QQ,[[randint(-5,5) for x in range(c)] for y in range(r)]))
我的问题是如何将这些矩阵添加到列表中?谢谢。
可以将事物添加到列表中
使用列表的 append
和 extend
方法。
示例:创建一个空列表并追加矩阵 在构建它们时使用它。
matrices = []
for _ in range(5):
c = randint(1, 10)
r = randint(1, 10)
m = Matrix(QQ, [[randint(-5, 5) for _ in range(c)] for _ in range(r)]))
matrices.append(m)
要直接构建列表,请使用 Python 的理解语法:
matrices = [
Matrix(QQ, [[randint(-5, 5) for _ in range(randint(1, 10))]
for _ in range(randint(1, 10))]))
for _ in range(5)
]
可以定义一个随机矩阵函数, 并用它来构建矩阵列表。
def my_random_matrix(emax=5, rmax=10, cmax=10):
r"""
Return a random matrix of random size.
The number of rows is picked at random between ``1`` and ``rmax``.
The number of columns is picked at random between ``1`` and ``cmax``.
The entries are integers picked at random between ``-emax`` and ``emax``.
The matrix is returned as a matrix over ``QQ``.
"""
r, c = randint(1, rmax), randint(1, cmax)
return Matrix(QQ, r, c, [randint(-emax, emax) for _ in range(r * c)])
matrices = [my_random_matrix() for _ in range(5)]