Sparse assignment list in python

前端 未结 2 1787
我在风中等你
我在风中等你 2020-11-28 15:37

I need a list with the following behavior

>>> l = SparseList()
>>> l
[]
>>> l[2] = \"hello\"
>>> l
[ None, None, \"hello\         


        
2条回答
  •  生来不讨喜
    2020-11-28 16:32

    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.

    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'

提交回复
热议问题