擅长:python、mysql、java
<p>你是否因为担心它的性能而回避了显而易见的答案(即<code>[[1, 2], [3, 4]]</code>)?{看,如果你在工作。最好的解决办法是不要重新发明你自己的轮子。在</p>
<p><strong>编辑:</strong>
如果你真的觉得有必要用你自己的方式来做,你可以像NumPy一样遵循一个<a href="http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html#internal-memory-layout-of-an-ndarray" rel="nofollow">strided index scheme</a>的方式,wihch可能会这样做:</p>
<pre><code>import operator
def product(lst):
return reduce(operator.mul, lst, 1)
class MyArray(object):
def __init__(self, shape, initval):
self.shape = shape
self.strides = [ product(shape[i+1:]) for i in xrange(len(shape)) ]
self.data = [initval] * product(shape)
def getindex(self, loc):
return sum([ x*y for x, y in zip(self.strides, loc) ])
def getloc(self, index):
loc = tuple()
for s in self.strides:
i = index // s
index = index % s
loc += (i,)
return loc
</code></pre>
<p>用作:</p>
^{pr2}$