Pergunta

class world:
    def __init__(self, screen_size):
        self.map = [[0 for col in range(500)] for row in range(500)]
        self.generate()

    def generate(self):
        for x in range(0, len(self.map[0])):
            for y in range(0, len(self.map)):
                kind = random.randint(0, 100)
                if kind <= 80:
                    self.map[x][y] = (random.randint(0, 255),random.randint(0, 255),random.randint(0, 255))
                else:
                    self.map[x][y] = (random.randint(0, 255),random.randint(0, 255),random.randint(0, 255))
        print self.map[50][50], self.map[-50][-50]
printing => (87, 92, 0) (31, 185, 156)

How is this possible that negative values aren't out of range? It should throw IndexError.

Foi útil?

Solução

Using negative numbers starts at the back of the list and counts down, that's why they still work.

Outras dicas

When you index into a list, the negative values mean N values from the end. So, -1 is the last item, -5 is the 5th from the end, etc. It's actually quite useful once you are used to it.

I think this can be best explained with a demonstration:

>>> a = [1, 2, 3, 4]
>>> a[-1]
4
>>> a[-2]
3
>>> a[-3]
2
>>> a[-4]
1
>>> # This blows up because there is no item that is
>>> # 5 positions from the end (counting backwards).
>>> a[-5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>

As you can see, negative indexes step backwards through the list.

To explain further, you can read section 3.7 of this link which talks about negative indexing with lists.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top