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

时间:2017-10-04 01:58:12

标签: 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, 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:列表分配索引超出范围"

1 个答案:

答案 0 :(得分:1)

看起来您的错误在if语句中。您未对directions列表编制索引 - 您尝试索引变量(rightleftupdown)因此错误。

试试这个:

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]