你的意思是像下面這樣的東西嗎?
class DynamicList(list):
def __getslice__(self, i, j):
return self.__getitem__(slice(i, j))
def __setslice__(self, i, j, seq):
return self.__setitem__(slice(i, j), seq)
def __delslice__(self, i, j):
return self.__delitem__(slice(i, j))
def _resize(self, index):
n = len(self)
if isinstance(index, slice):
m = max(abs(index.start), abs(index.stop))
else:
m = index + 1
if m > n:
self.extend([self.__class__() for i in range(m - n)])
def __getitem__(self, index):
self._resize(index)
return list.__getitem__(self, index)
def __setitem__(self, index, item):
self._resize(index)
if isinstance(item, list):
item = self.__class__(item)
list.__setitem__(self, index, item)
>>> mat = DynamicList()
>>> mat[0] = ['row1','row1','row1']
>>> mat[1] = ['row2','row2']
>>> mat[2]= ['row3']
>>> mat
[['row1', 'row1', 'row1'], ['row2', 'row2'], ['row3']]
>>> print mat[1][1]
row2
>>> mat[5][5] = 'row5'
>>> mat
[['row1', 'row1', 'row1'], ['row2', 'row2'], ['row3'], [], [], [[], [], [], [],
[], 'row5']]
>>> print mat[5]
[[], [], [], [], [], 'row5']
>>> print mat[5][5]
row5
Python中沒有真正的二維數組,但是您可以擁有一個列表列表。而且您無需事先指定大小。或者你真的在談論[Python數組](http://docs.python.org/library/array.html)? –
是的,我想定義Python數組。給我舉例說明如何定義列表whit的列表,並提前指定大小。感謝 –
我想這樣做: >>>墊= [] [] >>>墊[0] = [ 'ROW1', 'ROW1', 'ROW1'] >>>墊[1 ] = [ 'ROW2', 'ROW2'] >>>墊[2] = [ 'ROW3'] 並給值如下: >>>打印墊[1] [1] ROW2 –