您可以編寫一個列表視圖類型。下面是我自己編寫的實驗,它是由不保證完整或無缺陷的
class listview (object):
def __init__(self, data, start, end):
self.data = data
self.start, self.end = start, end
def __repr__(self):
return "<%s %s>" % (type(self).__name__, list(self))
def __len__(self):
return self.end - self.start
def __getitem__(self, idx):
if isinstance(idx, slice):
return [self[i] for i in xrange(*idx.indices(len(self)))]
if idx >= len(self):
raise IndexError
idx %= len(self)
return self.data[self.start+idx]
def __setitem__(self, idx, val):
if isinstance(idx, slice):
start, stop, stride = idx.indices(len(self))
for i, v in zip(xrange(start, stop, stride), val):
self[i] = v
return
if idx >= len(self):
raise IndexError(idx)
idx %= len(self)
self.data[self.start+idx] = val
L = range(10)
s = listview(L, 2, 5)
print L
print s
print len(s)
s[:] = range(3)
print s[:]
print L
輸出方式:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<listview [2, 3, 4]>
3
[0, 1, 2]
[0, 1, 0, 1, 2, 5, 6, 7, 8, 9]
您可以分配到指標在ListView,它會反思底層列表。但是,在listview上定義附加或類似的操作是沒有意義的。如果底層列表的長度發生變化,它也可能會中斷。
另請參閱http://stackoverflow.com/questions/3485475/can-i-create-a-view-on-a-python-list –