python中的稀疏赋值列表 [英] Sparse assignment list in python

查看:49
本文介绍了python中的稀疏赋值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个具有以下行为的列表

<预><代码>>>>l = SparseList()>>>升[]>>>l[2] = "你好">>>升[无,无,你好"]>>>升[5]没有任何>>>l[4] = 22>>>升[无,无,你好",无,22]>>>长度(升)5>>>for i in l: 打印 i没有任何没有任何你好"没有任何22

虽然它可以通过字典模拟",但并不完全相同.numpy 数组可以这样做,但我不想为这样的事情导入整个 numpy.在自己编写代码之前,我会询问标准库中是否存在类似的东西.

解决方案

这是传递给定示例的最少代码(进行了必不可少的调整:您希望奇怪的间距和引用,无"在没有 <代码>打印语句等):

class SparseList(list):def __setitem__(self, index, value):缺失 = 索引 - len(self) + 1如果丢失 >0:self.extend([无] * 缺失)list.__setitem__(self, index, value)def __getitem__(self, index):尝试:返回 list.__getitem__(self, index)除了索引错误:返回无__test__ = dict(allem='''>>>l = SparseList()>>>升[]>>>l[2] = "你好">>>升[无,无,'你好']>>>打印 l[5]没有任何>>>l[4] = 22>>>升[无,无,'你好',无,22]>>>长度(升)5>>>for i in l: 打印 i没有任何没有任何你好没有任何22''')导入文档测试doctest.testmod(详细= 1)

我想您会想要更多(以支持负索引、切片和其他任何内容),但这就是您的所有示例都隐式指定的内容.

I need a list with the following behavior

>>> l = SparseList()
>>> l
[]
>>> l[2] = "hello"
>>> l
[ None, None, "hello"]
>>> l[5]
None
>>> l[4] = 22
>>> l
[ None, None, "hello", None, 22]
>>> len(l)
5
>>> for i in l: print i
None
None
"hello"
None
22

Although it can "emulated" via a dictionary, it's not exactly the same. numpy array can behave this way, but I don't want to import the whole numpy for something like this. Before coding it myself, I ask if something similar exists in the standard library.

解决方案

Here's minimal code to pass your given examples (with indispensable adjustments: you expect weird spacing and quoting, 'None' to be printed out at the prompt without a print statement, etc etc):

class SparseList(list):
  def __setitem__(self, index, value):
    missing = index - len(self) + 1
    if missing > 0:
      self.extend([None] * missing)
    list.__setitem__(self, index, value)
  def __getitem__(self, index):
    try: return list.__getitem__(self, index)
    except IndexError: return None

__test__ = dict(allem='''
>>> l = SparseList()
>>> l
[]
>>> l[2] = "hello"
>>> l
[None, None, 'hello']
>>> print l[5]
None
>>> l[4] = 22
>>> l
[None, None, 'hello', None, 22]
>>> len(l)
5
>>> for i in l: print i
None
None
hello
None
22
''')
import doctest
doctest.testmod(verbose=1)

I imagine you'll want more (to support negative indices, slicing, and whatever else), but this is all your examples are implicitly specifying.

这篇关于python中的稀疏赋值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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