列表在python中是不可变的_Python中的不可变列表

I'm trying to make a list which is used throughout the application immutable. I thought wrapping this list in a tuple would do the trick, but it seems that tuple(list) doesn't actually wrap, but copies the list elements.

>>> a = [1, 2, 3, 4]

>>> b = tuple(a)

>>> b

(1, 2, 3, 4)

>>> a[0] = 2

>>> b # was hoping b[0] to be 2

(1, 2, 3, 4)

Is there an easy way of creating a list-backed "view" on this list that is immutable (wrt. operations on this view), but reflects any change that happened to the backing list?

I realise that this question has been asked before, but none of the responses address this view-backing list relationship (in fact some of the comments even suggest that tuples work the way I was hoping they do, but the above snippet suggests otherwise).

解决方案

If you don't want to copy the data, and want to pass an unchangeable "list" around, one way to do so is to create a proxy object, copy of a list, which disables all changing methods, and refer the reading methods to the original list - something along:

class ReadOnlyList(list):

def __init__(self, other):

self._list = other

def __getitem__(self, index):

return self._list[index]

def __iter__(self):

return iter(self._list)

def __slice__(self, *args, **kw):

return self._list.__slice__(*args, **kw)

def __repr__(self):

return repr(self._list)

def __len__(self):

return len(self._list)

def NotImplemented(self, *args, **kw):

raise ValueError("Read Only list proxy")

append = pop = __setitem__ = __setslice__ = __delitem__ = NotImplemented

And, of course, implement whatever other methods you judge necessary, either raising the error (or ignoring the writting instruction) - or acessing the corresponding object in the internal list.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值