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