引用列表的一部分-Python

2024-04-28 14:54:50 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我在python中有一个列表,如何创建对该列表一部分的引用?例如:

myList = ["*", "*", "*",  "*", "*", "*", "*", "*", "*"]

listPart = myList[0:7:3] #This makes a new list, which is not what I want

myList[0] = "1"

listPart[0]

"1"

这可能吗?如果可能的话,我该如何编码?

干杯, 乔


Tags: 编码which列表newisnotthiswhat
3条回答

您可以编写列表视图类型。这是我作为实验写的东西,它决不能保证是完整的或没有错误的

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上定义append或类似的操作是没有意义的。如果基础列表的长度发生变化,它也可能会中断。

在python中没有什么能真正满足您的需求。基本上你想写一些代理对象。

使用切片对象还是islice迭代器?

http://docs.python.org/library/functions.html#slice

相关问题 更多 >