我可以创建一个"查看"在Python列表? [英] Can I create a "view" on a Python list?
问题描述
我有一个大名单→
。我想创建一个从元素4至6视图我可以用序列切片做。
>>> L =范围(10)
>>> LV = L [3:6]
>>> LV
[3,4,5]
不过LV是升片的副本。如果我改变底层的名单,LV并不反映这一变化。
>>> L [4] = -1
>>> LV
[3,4,5]
反之亦然,我想在LV修改交运集团反映为好。其他比该列表的大小是不会改变的。
我不期待着建立一个大的类来做到这一点。我只希望其他的Python大师们可能知道一些隐藏的语言伎俩。理想情况下,我希望它可以像使用C指针运算。
INT LV [] = L + 3;
有在Python标准库中没有名单切片级(也没有一个内置)。所以,你需要一类,虽然它不一定是大的 - 尤其是如果你满足于一个只读和紧凑型片。例如:
导入收藏类ROListSlice(collections.Sequence): 高清__init __(自我,ALIST,开始,阿伦):
self.alist = ALIST
self.start =启动
self.alen =阿伦 高清__len __(个体经营):
返回self.alen 高清(指自我,我):
如果我℃的:我+ = self.alen
返回1 + self.start 高清__getitem __(自我,我):
返回self.alist [self.adj(ⅰ)]
这有一定的局限性(不支持切片切片),但对于大多数用途可能会确定。
为了使这个序列R / W,你需要添加 __ setitem __
, __ delitem __
和插入
:
类ListSlice(ROListSlice): 高清__setitem __(自我,I,V):
self.alist [self.adj(I)] = V 高清__delitem __(自我,I,V):
德尔self.alist [self.adj(ⅰ)]
self.alen - = 1 高清插入(自我,I,V):
self.alist.insert(self.adj(ⅰ),v)的
self.alen + = 1
I have a large list l
. I want to create a view from element 4 to 6. I can do it with sequence slice.
>>> l=range(10)
>>> lv=l[3:6]
>>> lv
[3, 4, 5]
However lv is copy of a slice of l. If I change the underlying list, lv does not reflect the change.
>>> l[4] = -1
>>> lv
[3, 4, 5]
Vice versa I want modification on lv reflect in l as well. Other than that the list size are not going to be changed.
I'm not look forward to build a big class to do this. I'm just hoping other Python gurus may know some hidden language trick. Ideally I hope it can like pointer arithmetic in C.
int lv[] = l + 3;
There is no "list slice" class in the Python standard library (nor is one built-in). So, you do need a class, though it need not be big -- especially if you're content with a "readonly" and "compact" slice. E.g.:
import collections
class ROListSlice(collections.Sequence):
def __init__(self, alist, start, alen):
self.alist = alist
self.start = start
self.alen = alen
def __len__(self):
return self.alen
def adj(self, i):
if i<0: i += self.alen
return i + self.start
def __getitem__(self, i):
return self.alist[self.adj(i)]
This has some limitations (doesn't support "slicing a slice") but for most purposes might be OK.
To make this sequence r/w you need to add __setitem__
, __delitem__
, and insert
:
class ListSlice(ROListSlice):
def __setitem__(self, i, v):
self.alist[self.adj(i)] = v
def __delitem__(self, i, v):
del self.alist[self.adj(i)]
self.alen -= 1
def insert(self, i, v):
self.alist.insert(self.adj(i), v)
self.alen += 1
这篇关于我可以创建一个&QUOT;查看&QUOT;在Python列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!