letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']#alphabet
bag_o_letters = []#letters to chose from
letter_count = [9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1]#random indexes to chose from
for x in range(26):#loops through the random index of letter_count
for i in range(letter_count[x]):#chooses the index
bag_o_letters.append(letters[x])#appends the index of the letter to bag_o_letters
rack = []#list for the person to see
for a in range(7):#makes the list 7 letters long
rack.append(bag_o_letters.pop(random.randint(0,len(letters)-1)))#appends the letter to rack(supposedly...)
print(rack)
在剛剛閱讀的代碼中,應該選擇隨機字母,並將這些字母中的7個放在可以看到的機架中。它顯示了我多次查看的錯誤,但我看不出錯在哪裏。fPython:從一個隨機的字母列表中創建一個新列表
I put comments on the side to understand the code.
它顯示了這個錯誤:
rack.append(bag_of_letters.pop(random.randint(0,len(letters)-1)))
IndexError: pop index out of range
Can someone please help?
After this code, I am going to make a input statement for the user to make a word from those letters.
'bag_o_letter'沒有足夠的元素來處理'pop'。 –
我不確定我是否理解你要做什麼,但是你的錯誤是由於你試圖用bag_of_letters中的一個隨機索引在區間[0..25]中彈出一個項目而引起的(因爲len(字母)-1 = 25),並且bag_of_letters僅在第一次迭代中包含單個項目。首先是 – dkasak
。你在bag_o_letters&bag_o_letter有一些錯別字。第二:「我」做什麼? –