python - 为 (mxn) 2d ndarray 的每一行自动生成 m 个变量
问题描述
假设我有 amxn numpy 矩阵,我需要为矩阵的每一行创建 m 个变量。有没有一种自动的方法来生成这些变量,然后在我的脚本中一次调用它们?
例如,而不是说
matrix = np.random.randn(5, 3)
a = matrix[0,:]
b = matrix[1,:]
c = matrix[2,:]
d = matrix[3,:]
e = matrix[4,:]
res = someOperation(a, b, c, d, e)
有没有办法为一些任意大小的矩阵自动生成这些变量,然后同时调用它们?我有一个包含大量行的矩阵,当然必须有一种更优雅的方式。
谢谢!
解决方案
一个选项是传入整个矩阵,然后传入内部,如果要将相同的方程应用于所有行,则可以按如下方式遍历行
def someOperation(matrix):
for row in matrix:
print(row)
matrix = np.random.randn(5, 3)
res = someOperation(matrix)
否则,如果您希望所有变量都作为字母,您可以做的最接近的是使用字典,如下所示,这只允许字母表中的字母数量,但如果您愿意,您可以随时重复字母。
import string
matrix = np.random.randn(5, 3)
alphabets = string.ascii_lowercase
matrixDictionary = {}
for i, row in enumerate(matrix):
matrixDictionary[alphabets[i]] = row
# example of how to access the key and row
for key in matrixDictionary.keys():
print(str(key) + " | " + str(matrixDictionary[key]))
推荐阅读
- python - 如何修复IndexError:python中的字符串索引超出范围
- java - 无法运行 java 文件(修复类路径时遇到问题)
- python-3.x - 如何修复:提交 Python 代码时,预期为 2 输出,但在 PASTA 上得到 0
- lightbox2 - 如何在 Lightbox v2.10.0 中链接 Youtube 视频
- docker - mesos + marathon组合中服务ip变化的解决方法能告诉我吗?
- java - 在杰克逊序列化后避免列表的类型信息
- angular - 异步修改数组 observable 中的每一项,并返回修改后的 observable
- javascript - 每隔几分钟编辑同一条消息
- php - 如何使用 PHP 代码将 XML 结果转换为 JSON 数组或 PHP 数组
- java - Postman 中应使用 ',' 而不是 't'