正在修复列表超出范围错误。python
我需要一个随机数1-3生成。我得到的错误是 索引器:列表索引超出范围 我的代码如下:正在修复列表超出范围错误。python,python,list,python-3.x,random,int,Python,List,Python 3.x,Random,Int,我需要一个随机数1-3生成。我得到的错误是 索引器:列表索引超出范围 我的代码如下: weaponList = [0,1,2] weapon2 = weaponList[random.randint(0,3)] 应该排队吗 randint(int1,int2)是包含的,所以两个数字都可以调用 索引从0开始,调用武器列表[0]将得到0,这是第0个索引。Python列表是。在您的示例中: >>> weaponList = [0,1,2] >>> weaponLi
weaponList = [0,1,2]
weapon2 = weaponList[random.randint(0,3)]
应该排队吗
randint(int1,int2)是包含的,所以两个数字都可以调用
索引从0开始,调用武器列表[0]将得到0,这是第0个索引。Python列表是。在您的示例中:
>>> 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
这将从
weaponList
中选择一个随机元素,因此您甚至不必与索引斗争。randint
包含在内,您需要(0,2)
。或random.randrange(len(weaponList))
或只是weapon2=random.choice(weaponList)
谢谢@MorganThrapp,这就是我想要的。
>>> 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
weapon2 = random.choice(weaponList)