参考列表的一部分 - Python

joe*_*joe 12 python list

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

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

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

myList[0] = "1"

listPart[0]

"1"
Run Code Online (Sandbox Code Playgroud)

这是可能的,如果是这样,我将如何编码?

干杯,乔

u0b*_*6ae 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
Run Code Online (Sandbox Code Playgroud)

输出:

[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]
Run Code Online (Sandbox Code Playgroud)

您可以在列表视图中分配索引,它会反映在基础列表上。但是,在列表视图上定义附加或类似操作是没有意义的。如果基础列表的长度发生变化,它也可能会中断。


Bas*_*ard 4

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

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