【问题标题】:Python, negative values aren't out of range in listPython,负值不在列表范围内
【发布时间】:2013-10-03 18:37:30
【问题描述】:
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)

负值怎么可能不会超出范围?它应该抛出 IndexError。

【问题讨论】:

  • 负索引向后索引列表 (l[-1] == l[len(l) - 1])。

标签: python list negative-number


【解决方案1】:

使用负数从列表的最后开始倒计时,这就是它们仍然有效的原因。

【讨论】:

    【解决方案2】:

    当您对列表进行索引时,负值表示从末尾开始的 N 个值。所以,-1 是最后一项,-5 是倒数第 5 个,等等。一旦你习惯了它,它实际上非常有用。

    【讨论】:

      【解决方案3】:

      我认为这可以通过演示来最好地解释:

      >>> 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
      >>>
      

      如您所见,负索引在列表中倒退

      为了进一步解释,您可以阅读此link 的第 3.7 节,其中讨论了使用列表进行负索引。

      【讨论】:

        猜你喜欢
        • 2021-12-13
        • 1970-01-01
        • 2016-01-28
        • 2016-12-28
        • 1970-01-01
        • 1970-01-01
        • 2011-04-17
        • 2012-01-22
        • 1970-01-01
        相关资源
        最近更新 更多