【问题标题】:Reference to Part of List - Python引用部分列表 - Python
【发布时间】:2010-12-19 19:18:29
【问题描述】:

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

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

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

myList[0] = "1"

listPart[0]

"1"

这可能吗?如果可以,我将如何编码?

干杯, 乔

【问题讨论】:

标签: python list


【解决方案1】:

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

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]

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

【讨论】:

    【解决方案2】:

    使用 slice 对象还是 islice 迭代器?

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        我认为这是不可能的。这会导致许多可能的错误,例如:当您附加引用更大列表的一部分的列表时会发生什么?大列表中的下一个元素应该被替换还是插入?

        据我所知,silce 是获取列表元素的内部机制。它们不会创建新的列表对象,而是引用旧列表对象的一部分。 Islice 只是迭代 slice 给出的元素,它也不是参考,而是实际的对象——改变它不会影响原始列表。还是我弄错了?

        正如评论中所说,该解决方案确实对 Bastien 先生有帮助,您可以这样做:

        sliceobject = slice(0,7,3)
        for i in xrange(sliceobject.start, sliceobject.stop, sliceobject.step)
            myList[i] = whatever
        

        这样您就可以通过引用访问列表中的每个指定元素。

        【讨论】:

        • 我认为你是对的。但在我看来,像元组(列表、切片)这样的东西似乎可以满足 OP 的需求。
        • 希望如此。其他选项可能是手动使用切片(for i in xrange(sliceobject.start, sliceobject.stop, sliceobject.step) mylist[i] = 不管)
        猜你喜欢
        • 2020-03-04
        • 2015-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多