2016-07-22 28 views
0

我有一個30個字符串的列表。我想使用隨機模塊的選擇方法,並從它們所存儲的列表中生成一個新字符串。我不想重複任何字符串,並且我想打印所有唯一字符串一次。我試圖做一個聊天機器人,但我只能得到1串打印一遍又一遍我每次運行該程序random.choice與清單

print("you are speaking with Donald Trump. If you wish to finish your conversation at any time, type good bye") 
greetings = ["hello", "hey", "what's up ?", "how is it going?", ] 
#phrase_list = ["hello", "the wisdom you seek is inside you", "questions are more important than answers"] 
random_greeting = random.choice(greetings) 

print(random_greeting) 
open_article = open(filePath, encoding= "utf8") 

read_article = open_article.read() 
toks = read_article.split('"') 
random_tok = random.choice(toks) 
conversation_length = 0 
responses = '' 

while True: #getting stuck in infinite loops get out and make interative 
    user_response = input(" ") 
    if user_response != "" or user_response != "good bye": 
     responses = responses + user_response 
     conversation_length = conversation_length + 1 
    while conversation_length < 31: 

     print(random_tok) 
    if conversation_length >= 31: 
     print("bye bye") 
+0

能否請您包括你的代碼片段呢? – Unni

+0

我添加了上面的代碼。它不顯示它,但我在程序開始時隨機導入,只是沒有粘貼 – reubs

回答

0

你需要「隨機選擇無需更換。」這個在字符串列表上調用的函數將返回一個隨機字符串。不止一次調用,它不會返回相同的項目。

import random 

def choose_one(poss): 
    """ 
    Remove a randomly chosen item from the given list, 
    and return it. 
    """ 
    if not poss: 
     raise ValueError('cannot choose from empty list') 
    i = random.randint(0, len(poss) - 1) 
    return poss.pop(i) 
+0

非常感謝 – reubs

+2

爲什麼要用'pop()'而不是'random.sample'或' random.shuffle'? – TigerhawkT3

+1

由於random.sample()對單個調用實現了「無替代選擇」,但不修改底層列表,因此「無替代」條件不適用於多個調用。 'random.shuffle()'隨機化列表的順序,但不從沒有替換的列表中選擇。任何一個API都可以依賴於OP的原始程序,但是這個功能很簡單,容易理解,而且很有啓發性,並且可以解決OP的問題,特別是,第一段所述的核心問題。 –

0

請勿使用random.choice()。改爲使用random.shuffle()來代替隨機順序(唯一)的單詞,然後重複從該列表中取出。這確保了),你使用的所有的話,和b)不重複任何選秀權:

random_greetings = greetings[:] # create a copy 
random.shuffle(random_greetings) 

,然後每當你想要一個隨機單詞,只需使用:

random_greeting = random.greetings.pop()