Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.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_Python 3.x_Random - Fatal编程技术网

Python 随机生成要在图形上使用的整数

Python 随机生成要在图形上使用的整数,python,python-3.x,random,Python,Python 3.x,Random,该程序的功能是为变量右、左、上、下随机生成1-10的数字,用于40 x40图形。为了得到一个包含x和y变量的2个数字的列表,我有另一个随机数生成器来选择将要选择的 import random choice_x = random.randint(0, 1) choice_y = random.randint(0, 1) right = random.randint(10, 20) left = random.randint(0, 10) up = left = random.randint(0,

该程序的功能是为变量右、左、上、下随机生成1-10的数字,用于40 x40图形。为了得到一个包含x和y变量的2个数字的列表,我有另一个随机数生成器来选择将要选择的

import random
choice_x = random.randint(0, 1)
choice_y = random.randint(0, 1)
right = random.randint(10, 20)
left = random.randint(0, 10)
up = left = random.randint(0, 10)
down = left = random.randint(10, 20)
directions = [right, left, up, down]

if choice_x == 0:
  del directions[right]
elif choice_x == 1:
  del directions[left]

if choice_y == 0:
  del directions[up]
elif choice_y == 1:
 del directions[down]
 print (directions)

每当我尝试执行此代码时,都会收到一条消息,指出“IndexError:list assignment index out of range”

看起来您的错误在if语句中。您没有索引
方向
列表-您试图索引变量(
),因此出现错误

试试这个:

if choice_x == 0: del directions[0]
elif choice_x == 1: del directions[1]

if choice_y == 0: del directions[2]
elif choice_y == 1: del directions[3]

您试图用
删除方向[右]
做什么?您使用的索引不正确<代码>上、下、左、右是值,其值大于
len(方向)
。例如
down=randint(10,20)
表示
down>len(directions)
,因为
len(directions)
是4,而
down>=10