给从列表中随机选择的变量一个特定的字符串值

2024-06-16 18:15:33 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我现在正在做一个抽搐脚趾游戏,你和电脑玩,我似乎不明白这部分。我想让计算机从一个尚未使用的位置列表中选择一个随机变量,并使该变量的值为O。这是我目前拥有的

#positions is a list of variables that start off = ''

positions = [ul, uc, ur, cl, cc, cr, ll, lc, lr]

comchoice = randrange(0, len(positions))

while positions[comchoice] != '':
    comchoice = randrange(0, len(positions))
else:
    positions[comchoice] = 'O'

编辑:这个问题与据说是重复的问题不同。这是不同的,因为它是关于更改列表中变量的值。很明显,在我的帖子里,我用我的代码理解了重复帖子的问题


Tags: of游戏列表lenthatis计算机variables
1条回答
网友
1楼 · 发布于 2024-06-16 18:15:33

这对我有用:

from random import randrange

positions = ['']*9

comchoice = randrange(0, len(positions))

while positions[comchoice] != '':
    comchoice = randrange(0, len(positions))
else:
    positions[comchoice] = 'O'

print(positions)

生产:

['', '', '', 'O', '', '', '', '', '']

相关问题 更多 >