对称可寻址矩阵
我正在寻找在Python中创建具有对称寻址的二维整数矩阵(即矩阵[2,3]和矩阵[3,2]将返回相同的值)。整数将进行加法和减法,并用于逻辑比较。我最初的想法是预先创建整数对象,并尝试用一些相当于 Python 的指针来填充列表列表。但我不知道该怎么做。实现此目的的最佳方法是什么?我应该使用列表还是其他数据结构?
I'm looking to create a 2d matrix of integers with symmetric addressing ( i.e. matrix[2,3] and matrix[3,2] will return the same value ) in python. The integers will have addition and subtraction done on them, and be used for logical comparisons. My initial idea was to create the integer objects up front and try to fill a list of lists with some python equivalent of pointers. I'm not sure how to do it, though. What is the best way to implement this, and should I be using lists or another data structure?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Golub 和 Van Loan 的“矩阵计算”一书概述了一种可行的寻址方案:
将数据打包到向量中并按如下方式访问,假设 i >= j:
Golub and Van Loan's "Matrix Computations" book outlines a feasible addressing scheme:
You pack the data in to a vector and access as follows, assuming i >= j:
使用完整的方 numpy 矩阵可能会更好。是的,它浪费了一半的内存来存储冗余值,但是在 Python 中滚动你自己的对称矩阵会通过将整数存储和处理为 Python 对象来浪费更多的内存和 CPU。
You're probably better off using a full square numpy matrix. Yes, it wastes half the memory storing redundant values, but rolling your own symmetric matrix in Python will waste even more memory and CPU by storing and processing the integers as Python objects.
一种更简单、更干净的方法是仅使用以排序元组作为键的字典。这些元组与您的矩阵索引相对应。重写
__getitem__
和__setitem__
以按排序元组访问字典;这是一个示例类:然后像这样使用它:
A simpler and cleaner way is to just use a dictionary with sorted tuples as keys. The tuples correspond with your matrix index. Override
__getitem__
and__setitem__
to access the dictionary by sorted tuples; here's an example class:And then use it like this:
您只需要存储矩阵的下三角形。通常,这是通过一个 n(n+1)/2 长度的列表来完成的。您需要重载
__getitem__
方法来解释该条目的含义。You only need to store the lower triangle of the matrix. Typically this is done with one n(n+1)/2 length list. You'll need to overload the
__getitem__
method to interpret what the entry means.