擅长:python、mysql、java
<p>我认为Theano向量的<code>__getitem__</code>方法需要一个元组作为参数!像这样:</p>
<pre><code>class Vect (object):
def __init__(self,data):
self.data=list(data)
def __getitem__(self,key):
return self.data[key[0]:key[1]+1]
a=Vect('hello')
print a[0,2]
</code></pre>
<p>这里<code>print a[0,2]</code>当<code>a</code>是普通列表时,将引发异常:</p>
<pre><code>>>> a=list('hello')
>>> a[0,2]
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: list indices must be integers, not tuple
</code></pre>
<p>但是这里的<code>__getitem__</code>方法不同,它接受元组作为参数。</p>
<p>您可以将<code>:</code>符号传递给<code>__getitem__</code>,如下所示,<code>:</code>表示<em>切片</em>:</p>
<pre><code>class Vect (object):
def __init__(self,data):
self.data=list(data)
def __getitem__(self,key):
return self.data[0:key[1]+1]+list(key[0].indices(key[1]))
a=Vect('hello')
print a[:,2]
</code></pre>
<p>谈到<code>None</code>,它也可以在用普通Python编制索引时使用:</p>
<pre><code>>>> 'hello'[None:None]
'hello'
</code></pre>