Array in python with arbitrary index

I'm starting a python. I want to have arrays with an arbitrary index from pto q, not from 0.

How to create an array with q-p+1elements with an index from pto q?

+4
source share
4 answers

You can create a subclass listthat sets up the index to access the element:

class ListWithOffset(list):
    def __init__(self, offset, *a, **kw):
        self.offset = offset
        super().__init__(*a, **kw)

    def __getitem__(self, i):
        return super().__getitem__(self, self._adjust_idx(i))

    def __setitem__(self, i, value):
        return super().__setitem__(self, self._adjust_idx(i), value)

    def __delitem__(self, i):
        return super().__delitem__(self, self._adjust_idx(i))

    def _adjust_idx(self, i):
        if isinstance(i, slice):
            return slice(i.start - self.offset if i.start is not None else None,
                         i.stop - self.offset if i.stop is not None else None,
                         i.step)
        else:
            return i - self.offset

(change: forgot to process the slice)

Note that there is no need to specify the ending index explicitly. It can change as your list changes in size and can be defined as mylist.offset + len(mylist)at any given time.

, , , . ( list ), , , .

+6

, . , . :

p = 10
q = 20
lst = [None for _ in range(q-p+1)] # initialize a list for the desired range

idx :

lst[idx-p]

:

lst[10-p] = 100
lst[10-p]
=> 100

lst[20-p] = 200
lst[20-p]
=> 200

:

[100, None, None, None, None, None, None, None, None, None, 200]
+4
  • :

    d = {}
    for i in range(5, 10):
        d[i] = "something"+`i`
    
  • :

    d = {i:"something"+`i` for i in range(5, 10)}
    
  • OrderedDict, :

    from collections import OrderedDict
    d = OrderedDict
    for i in range(5, 10):
        d[i] = "something"+`i`
    

, ( ):

print d[7]

: something7

OrderedDict ( ):

for x in d.values():
    print x

:

something5
something6
something7
something8
something9
+1
source

You cannot do this with a list (and suppose you do not want to use a dictionary because you want to arrange the elements) - however, you can imitate it.

p = 10
q = 20
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#takes in index from 10 to 19 - throws exception otherwise
def get_elem(index):
    index = index-p
    if index > 0 and index < len(l):
        return l[index-p]
    else: 
        raise IndexError("list index out of range") 

print get_elem(13) #  prints 4
0
source

Source: https://habr.com/ru/post/1548227/


All Articles