如何从列表中随机选择一个变量,然后在python中修改它?

mon*_*z09 4 python random list python-3.x

这是我的python 3代码.我想随机选择一个单元格变量(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
Run Code Online (Sandbox Code Playgroud)

我在"random.choice(cells)"上收到"无法分配函数调用"错误.我假设我只是错误地使用它?我知道您可以使用随机选择来更改变量,如下所示:

import random
options = ["option1", "option2"]
choice = random.choice(options)
Run Code Online (Sandbox Code Playgroud)

Sai*_*ait 7

问题:

random.choice(cells)例如"3",从列表中返回一个随机值,并且您正在尝试为其分配内容,例如:

"3" = "X"
Run Code Online (Sandbox Code Playgroud)

这是错的.

而不是这个,你可以修改list,例如:

cells[5] = "X"
Run Code Online (Sandbox Code Playgroud)

解:

你可以用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)
Run Code Online (Sandbox Code Playgroud)

输出:

['1', '2', '3', '4', '5', '6', '7', '8', '9']
['1', '2', '3', '4', '5', '6', '7', 'X', '9']
Run Code Online (Sandbox Code Playgroud)