Sco*_*God 0 python indexing syntax list python-3.x
在提出这个问题之后,我扩展了接受的答案,使其适用于二维列表:
class List(list):
def __call__(self, i):
def call(j):
return self[i][j]
return call
Run Code Online (Sandbox Code Playgroud)
和三维列表:
class List(list):
def __call__(self, i):
def call2(j):
def call3(k):
return self[i][j][k]
return call3
return call2
Run Code Online (Sandbox Code Playgroud)
但是如何为n维列表实现这个类呢?
如果索引值本身是一个Sequence类型,则可以返回"可调用列表" 类型:
from collections import Sequence
class List(list):
def __call__(self, i):
res = self[i]
if isinstance(res, Sequence) and not isinstance(res, str):
res = type(self)(res)
return res
Run Code Online (Sandbox Code Playgroud)
这确保了任何可以与解决[..]索引语法现在可以用一个解决(..)调用语法也是如此.
我豁免了字符串; 这些也是序列,但您可能不希望将其扩展到这些值.
演示:
>>> from collections import Sequence
>>> class List(list):
... def __call__(self, i):
... res = self[i]
... if isinstance(res, Sequence) and not isinstance(res, str):
... res = type(self)(res)
... return res
...
>>> a = List([[['foo']]])
>>> a(0)
[['foo']]
>>> a(0)(0)(0)
'foo'
Run Code Online (Sandbox Code Playgroud)