引用列表的一部分-Python [英] Reference to Part of List - Python

查看:158
本文介绍了引用列表的一部分-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a list in python, how can I create a reference to part of the list? For example:

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

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

myList[0] = "1"

listPart[0]

"1"

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

Is this possible and if so how would I code it?

干杯, 乔

推荐答案

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

You can write a list view type. Here is something I have written as experiment, it is by no means guaranteed to be complete or bug-free

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]

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

You may assign to indices in the listview, and it will reflect on the underlying list. However,it does not make sense to define append or similar actions on the listview. It may also break if the underlying list changes in length.

这篇关于引用列表的一部分-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆