2014-01-19 40 views
0

問題是從已定義的單詞列表中選擇一個隨機單詞,然後從列表中刪除該單詞。計算機應該顯示混亂的單詞並要求用戶猜測該單詞是什麼。一旦玩家猜出了這個單詞,應該從列表中選擇另一個隨機單詞,遊戲繼續進行,直到單詞列表爲空。Python:從列表中選擇隨機單詞,然後將其刪除

當我運行它時,我有一個錯誤。

Traceback (most recent call last): 
    File "F:\Computer Science\Unit 3\3.6\3.6 #5.py", line 21, in <module> 
    word_jamble (random_word) 
    File "F:\Computer Science\Unit 3\3.6\3.6 #5.py", line 14, in word_jamble 
    word = list(word) 
TypeError: 'list' object is not callable 

這是我的計劃

list = ['mutable', 'substring', 'list', 'array', 'sequence'] 

from random import shuffle 

def word_jamble(word): 
    word = list(word) 
    shuffle(word) 
    print ''.join(word) 

from random import choice 

random_word = choice(list) 
word_jamble (random_word) 
user_input = raw_input("What's the word? ") 
if user_input == choice(list): 
    del list[index(choice(list))] 
+2

請發表您的具體問題。 – Christian

+1

我想我們是該程序的擴展版本的用戶:我們應該猜測問題是什麼。嗯? –

回答

2

你應該改變你的第一個變量,list,到別的東西。它與內置列表類型混淆,並且您的list對象當然不可調用。

+0

它仍然有一個錯誤 – user3161743

+0

什麼是新的錯誤? – tayfun

0

這意味着正是它說:

TypeError: 'list' object is not callable 

這是因爲在此階段

word = list(word) 

抱怨,

list = ['mutable', 'substring', 'list', 'array', 'sequence'] 

已經發生了。

一旦您爲list創建該特定列表的名稱,它就不能再是內置的list類的名稱。一個名字一次只能命名一件事。

1

主要問題是變量名稱list。它是內建類型構造函數的名稱。當您使用say list時,它會隱藏內置類型的名稱。除此之外,您可以使用pop方法,這樣,得到隨機單詞淘汰之列的易

words_list = ['mutable', 'substring', 'list', 'array', 'sequence'] 
import random 
while words_list: 
    print words_list.pop(random.randrange(len(words_list))) 
0

有幾個基本問​​題的代碼:

list = ['mutable', 'substring', 'list', 'array', 'sequence'] 

list是列表構造函數。你應該永遠不會命名您的變量後的python關鍵字。


del list[index(choice(l))] 

del是很少需要在蟒蛇。我的建議是,如果你是一個開墾者,你應該完全忘記它。除去列表元素的正確方式是使用兩種list.remove(基於要素平等的)或者list.pop(基於索引)


def word_jamble(word): 
    word = list(word) 
    shuffle(word) 
    print ''.join(word) 

在這裏,您使用的功能,以實現到不同的任務:洗牌一個字,並打印出來。通常,讓每個函數只執行特定任務是一個很好的做法 - 這會導致更多的可重用和有組織的代碼。不要在函數內部打印結果,而應考慮將其返回並打印到外部。


from random import shuffle 
# some code 
from random import choice 

這是很好的做法,讓您的進口在一起,並在你的程序的beggining。如果你從同一模塊中導入兩個元素,您可以用逗號分隔它們:

from random import shuffle, choice 

最後,由於要重複遊戲,直到沒有剩下的話,你需要使用一個週期:

while len(word_list)>0: # can be written simply as "while len(word_list):" 
    #your code here 
相關問題