How to create python list with negative index

I am new to python and you need to create a list with a negative index, but have failed so far.

I am using this code:

a = []
for i in xrange( -20, 0, -1 ):
    a[i] = -(i)
    log.info('a[{i}]={v}'.format(i=i, v=a[i]))
else:
    log.info('end')

and get the log output as

end

By the way, I use the site call quantizer, so log.info is from their infrastructure and just prints the output in the web console.

What am I doing wrong?

Thanks in advance for your help.

+4
source share
4 answers

If you are using Quantopian, it is advisable that you become familiar with numpy and pandas. For instance:

>>> import numpy as np 
>>> -1*np.arange(20)

array([  0,  -1,  -2,  -3,  -4,  -5,  -6,  -7,  -8,  -9, -10, -11, -12,
       -13, -14, -15, -16, -17, -18, -19])

Then you will have a[1]==-1, a[5]==-5etc.

+1
source

The only thing that strikes me is

 for i in xrange( -20, 0, -1 ):

, - ... -1 , -20, -21

-

a = []
a[0] = 5

a = [None]*20

0

:

xrange( -20, 0, -1 )

-20 0 () (.. -21, -22 ..). "" , - . ( range, ):

[...], , - + * , .

, , (, , - Python) - , - . - .

If you can tell us what result you expect, we can help you fix both of these problems.

0
source

You cannot create a list with negative indices. They start at zero and are counted at 1. If you use a negative index when accessing an element, Python will convert it to a positive index relative to the end of the list.

>>> a = [1, 2, 3]
>>> a[0]
1
>>> a[2]
3
>>> a[-1]   # Same as a[len(a)-1]
3

If you need negative indexes, you will have to use a dict that supports arbitrary (hashed) keys.

0
source

All Articles