Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
正在修复列表超出范围错误。python_Python_List_Python 3.x_Random_Int - Fatal编程技术网

正在修复列表超出范围错误。python

正在修复列表超出范围错误。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

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

索引器:列表索引超出范围

我的代码如下:

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)