python python中的稀疏赋值列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1857780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sparse assignment list in python
提问by Stefano Borini
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.
虽然它可以通过字典“模拟”,但并不完全相同。numpy 数组可以以这种方式运行,但我不想为这样的事情导入整个 numpy。在自己编码之前,我会问标准库中是否存在类似的东西。
回答by Alex Martelli
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):
这是传递给定示例的最少代码(进行了必不可少的调整:您希望奇怪的间距和引用,在没有print
声明的情况下在提示符下打印出“无”等):
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.
我想你会想要更多(支持负索引、切片和其他任何东西),但这是你的所有示例都隐含地指定。
回答by htmldrum
Dictionaries can be used as sparse lists. Whilst they will not provide the characteristics you are after (as you are not actually after a sparse list, all the list elements are complete references to None in a dynamically-sized Array), they act as a textbook sparse array.
字典可以用作稀疏列表。虽然它们不会提供您所追求的特征(因为您实际上并不是在追求稀疏列表,所有列表元素都是对动态大小数组中 None 的完整引用),但它们充当教科书稀疏数组。
sparse_vars = [(0,"Hi"),(10000,"Bye"),(20000,"Try")] sparse_list = {} for var in sparse_vars: sparse_list[var[0]] = var[1] >>> print sparse_list {0: 'Hi', 10000: 'Bye', 20000: 'Try'} >>> print sparse_list[20000] 'Try'