【问题标题】:Fixing list out of range error. Python [duplicate]修复列表超出范围错误。 Python [重复]
【发布时间】:2016-10-19 19:06:09
【问题描述】:

我需要生成一个随机数 1 - 3。我得到的错误是

IndexError: 列表索引超出范围

我的代码如下:

weaponList = [0,1,2]
weapon2 = weaponList[random.randint(0,3)]

【问题讨论】:

  • randint 包含在内,你要(0,2)
  • random.randrange(len(weaponList)) 或只是weapon2 = random.choice(weaponList)
  • 谢谢@MorganThrapp,这就是我想要的。

标签: python list python-3.x random int


【解决方案1】:
weapon2 = weaponList[random.randint(0,2)]

应该是行 randint(int1,int2) 包含在内,所以两个数都可以调用。

索引从 0 开始,调用 Wea​​ponList[0] 会得到 0,它位于第 0 个索引处。

【讨论】:

    【解决方案2】:

    Python 列表是zero indexed。在您的示例中:

    >>> weaponList = [0,1,2]
    >>> weaponList[0]
    0
    >>> weaponList[1]
    1
    >>> weaponList[2]
    2
    >>> weaponList[3]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: list index out of range
    

    因此,您必须选择一个介于零和两个random.randint(0,2) 之间的数字,如@9​​87654325@ is inclusive

    @Tadhg McDonald-Jensen 提出了一个更清洁的解决方案,在此处添加以供未来的读者阅读。

    weapon2 = random.choice(weaponList)
    

    这将从weaponList 中选择一个随机元素,因此您甚至不必为索引而烦恼。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 2013-04-07
      • 2019-10-01
      • 1970-01-01
      • 2019-10-13
      相关资源
      最近更新 更多