__getitem__,列表中有切片 [英] __getitem__ with slices on a list of lists
问题描述
我正在创建一个代表列表列表的类. __getitem__使我头疼.一切都进行得很顺利,直到我引入slice作为参数为止.
I'm creating a class representing a list of lists. __getitem__ is giving me headaches. Everything goes swimmingly until I introduce slices as parameters.
演示代码
# Python version 2.7.5
class NestedLists:
_Cells = [['.', '.', '.', '.', '.'],
['.', '.', 'N', '.', '.'],
['.', 'C', 'A', 'T', '.'],
['.', '.', 'P', '.', '.'],
['.', '.', '.', '.', '.']]
def __getitem__(self, index):
if isinstance(index, int):
return self._Cells[index]
elif isinstance(index, slice):
return self._Cells[index]
else:
raise TypeError, "Invalid argument type"
nested = NestedLists()
print "Expecting A"
print nested[2][2]
print "Expecting CAT"
print nested[2][1:4]
print "Expecting ..N.."
print " .CAT."
print " ..P.."
print nested[1:4]
print "Expecting .N."
print " CAT"
print " .P."
print nested[1:4][1:4]
下面的输出
Expecting A
A
Expecting CAT
['C', 'A', 'T']
Expecting ..N..
.CAT.
..P..
[['.', '.', 'N', '.', '.'], ['.', 'C', 'A', 'T', '.'], ['.', '.', 'P', '.', '.']]
Expecting .N.
CAT
.P.
[['.', 'C', 'A', 'T', '.'], ['.', '.', 'P', '.', '.']]
显然,正在发生的是第二个[]运算符调用被应用到第一个[...]操作符的输出,但仍位于最外层列表的上下文中.但是,解决方案使我难以理解.
Apparently, what is happening is that the second [] operator call is being applied to the output of the first... but staying in the context of the outermost list. The solution eludes me however.
推荐答案
您可能希望将多维访问的语法从obj[row][col]
更改为使用单个元组索引:obj[row, col]
.这是numpy
的ndarray
类型使用的格式,它非常有用,因为它使您可以立即查看索引的所有维度.您可以编写__getitem__
,以便进行任意尺寸的切片:
You probably want to change your syntax for mutidimensional access from obj[row][col]
to using a single tuple index: obj[row, col]
. This is the format numpy
's ndarray
type uses, and its very helpful, as it lets you see all the dimentions of the index at once. You can write a __getitem__
that will allow slicing in any dimension:
def __getitem__(self, index):
row, col = index
if isinstance(row, int) and isinstance(col, (int, slice)):
return self._Cells[row][col]
elif isinstance(row, slice) and isinstance(col, (int, slice)):
return [r[col] for r in self._Cells[row]]
else:
raise TypeError, "Invalid argument type"
这篇关于__getitem__,列表中有切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!