如何从列表中随机选择一个变量,然后在python中对其进行修改? [英] How do I randomly select a variable from a list, and then modify it in python?

查看:214
本文介绍了如何从列表中随机选择一个变量,然后在python中对其进行修改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的python 3代码.我想随机选择一个单元变量(c1至c9)并将其值更改为与cpuletter变量相同.

Here's my python 3 code. 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.

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

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

I'm getting a "Can't assign to function call" error on the "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)从列表中返回一个随机值,例如"3",并且您正在尝试为其分配某些内容,例如:

Problem:

random.choice(cells) returns a random value from your list, for example "3", and you are trying to assign something to it, like:

"3" = "X"

这是错误的.

相反,您可以修改list,例如:

Instead of this, you can modify the list, for example:

cells[5] = "X"

解决方案:

您可以使用 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)

输出:

['1', '2', '3', '4', '5', '6', '7', '8', '9']
['1', '2', '3', '4', '5', '6', '7', 'X', '9']

这篇关于如何从列表中随机选择一个变量,然后在python中对其进行修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆