Use of None in Array indexing in Python

前端 未结 2 1587
渐次进展
渐次进展 2021-01-03 20:57

I am using the LSTM tutorial for Theano (http://deeplearning.net/tutorial/lstm.html). In the lstm.py (http://deeplearning.net/tutorial/code/lstm.py) file, I don\'t understan

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-03 21:52

    I think the Theano vector's __getitem__ method expects a tuple as an argument! like this:

    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]
    

    Here print a[0,2] when a is an ordinary list will raise an exception:

    >>> a=list('hello')
    >>> a[0,2]
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: list indices must be integers, not tuple
    

    But here the __getitem__ method is different and it accepts a tuple as an argument.

    You can pass the : sign to __getitem__ like this as : means slice:

    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]
    

    Speaking about None, it can be used when indexing in plain Python as well:

    >>> 'hello'[None:None]
    'hello'
    

提交回复
热议问题