简体   繁体   English

随机生成用于图形的整数

[英]Randomly generating integers to be used on a graph

the function of this program is to randomly generate numbers ranging from 1-10 for the variables right, left, up, down to be used on a 40 x40 graph.该程序的功能是为变量右、左、上、下随机生成 1-10 之间的数字,以用于 40 x40 图形。 in order to have a list containing 2 numbers for the x and y variables, i have another random number generator that picks which will be chosen为了有一个包含 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)

whenever i try to execute this code, i keep getting a message stating "IndexError: list assignment index out of range"每当我尝试执行此代码时,我都会收到一条消息,指出“IndexError:列表分配索引超出范围”

Looks like your error is within the if statements.看起来您的错误在 if 语句中。 You're not indexing the directions list - you're trying to index a variable ( right , left , up , down ), hence the error.你没有索引directions列表 - 你试图索引一个变量( rightleftupdown ),因此错误。

Try this:尝试这个:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM