![](/img/trans.png)
[英]I can select randomly from a list… but how do I use this as a variable for different commands? Python
[英]How do I randomly select a variable from a list, and then modify it in python?
這是我的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
我在“random.choice(cells)”上收到“無法分配函數調用”錯誤。 我假設我只是錯誤地使用它? 我知道您可以使用隨機選擇更改變量,如下所示:
import random
options = ["option1", "option2"]
choice = random.choice(options)
random.choice(cells)
從列表中返回一個隨機值,例如"3"
,並且您正在嘗試為其分配內容,例如:
"3" = "X"
這是錯的。
而不是這樣,您可以修改list
,例如:
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']
Random.choice(cells)
從cells
Random.choice(cells)
返回一個隨機元素 ,所以如果它返回元素#0而元素#0是值"1"
,那么你的原始語句基本上會說"1" = "X"
- 顯然你可以' t將字符串文字指定為其他內容,它不是變量。
你想要得到一個隨機元素# ,然后分配cells[rand_elt_num]
。 您可以通過以下內容獲取隨機元素編號:
rand_elt_num = random.randint(0, len(cells)-1 ) #get index to a random element
cells[rand_elt_num] = "X" # assign that random element
我認為這與其他答案所說的相同,他們只是使用random.randrange()
代替。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.