[英]How do I randomly select a variable from a list, and then modify it in python?
Here's my python 3 code. 这是我的python 3代码。 I would like to randomly select one of the cell variables (c1 through c9) and change its value to the be the same as the cpuletter variable.
我想随机选择一个单元格变量(c1到c9)并将其值更改为与cpuletter变量相同。
import random
#Cell variables
c1 = "1"
c2 = "2"
c3 = "3"
c4 = "4"
c5 = "5"
c6 = "6"
c7 = "7"
c8 = "8"
c9 = "9"
cells = [c1, c2, c3, c4, c5, c6, c7, c8, c9]
cpuletter = "X"
random.choice(cells) = cpuletter
I'm getting a "Can't assign to function call" error on the "random.choice(cells)." 我在“random.choice(cells)”上收到“无法分配函数调用”错误。 I assume I'm just using it incorrectly?
我假设我只是错误地使用它? I know you can use the random choice for changing a variable like below:
我知道您可以使用随机选择更改变量,如下所示:
import random
options = ["option1", "option2"]
choice = random.choice(options)
random.choice(cells)
returns a random value from your list, for example "3"
, and you are trying to assign something to it, like: random.choice(cells)
从列表中返回一个随机值,例如"3"
,并且您正在尝试为其分配内容,例如:
"3" = "X"
which is wrong. 这是错的。
Instead of this, you can modify the list
, for example: 而不是这样,您可以修改
list
,例如:
cells[5] = "X"
You can use random.randrange()
. 您可以使用
random.randrange()
。
import random
cells = [str(i) for i in range(1,10)] # your list
cpuletter = 'X'
print(cells)
random_index = random.randrange(len(cells)) # returns an integer between [0,9]
cells[random_index] = cpuletter
print(cells)
Output: 输出:
['1', '2', '3', '4', '5', '6', '7', '8', '9']
['1', '2', '3', '4', '5', '6', '7', 'X', '9']
Random.choice(cells)
returns a random element from cells
, so if it returned element #0 and element #0 was the value "1"
, your original statement would essentially be saying "1" = "X"
- obviously you can't assign the string literal to be something else, it's not a variable. Random.choice(cells)
从cells
Random.choice(cells)
返回一个随机元素 ,所以如果它返回元素#0而元素#0是值"1"
,那么你的原始语句基本上会说"1" = "X"
- 显然你可以' t将字符串文字指定为其他内容,它不是变量。
You'd instead want to get a random element # , and assign cells[rand_elt_num]
. 你想要得到一个随机元素# ,然后分配
cells[rand_elt_num]
。 You could get the random element number by something simply like: 您可以通过以下内容获取随机元素编号:
rand_elt_num = random.randint(0, len(cells)-1 ) #get index to a random element
cells[rand_elt_num] = "X" # assign that random element
I think this is the same as what the other answer says, they just used random.randrange()
instead. 我认为这与其他答案所说的相同,他们只是使用
random.randrange()
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.