引用列表的一部分 - Python

13 投票
4 回答
11466 浏览
提问于 2025-04-15 16:20

如果我在Python中有一个列表,我该如何创建一个指向列表部分内容的引用呢?比如:

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

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

myList[0] = "1"

listPart[0]

"1"

这可能吗?如果可以,我该怎么写代码呢?

谢谢,

4 个回答

3

在Python里,没有什么东西能完全满足你的需求。简单来说,你想要写一个代理对象。

4

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

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

5

你可以写一个列表视图类型。这是我作为实验写的一些东西,绝对不能保证它是完整的或没有错误的。

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]

你可以给列表视图中的索引赋值,这样它会在底层列表中反映出来。不过,在列表视图上定义添加或类似的操作是没有意义的。如果底层列表的长度发生变化,它可能也会出问题。

撰写回答