2016-07-22 6 views
0

私は30文字列のリストを持っています。私は、ランダムモジュールのchoiceメソッドを使い、格納されているリストから新しい文字列を生成したいと思います。文字列を繰り返したくないので、すべての一意の文字列を一度印刷したいと思います。私はチャットボットを作成しようとしていますが、私は唯一のオーバー印刷する1つの文字列を取得することができ、すべての時間をかけて、私はあなたが必要random.choice with list

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

'random.sample'や' random.shuffle'? – TigerhawkT3

+1

'random.sample()'は1回の呼び出しに対して「置換なしの選択」を実装しているため、基になるリストは変更されないため、「置き換えなし」の条件は複数の呼び出しで保持されません。 'random.shuffle()'はリストの順序をランダム化しますが、置換えなしではリストから選択しません。いずれのAPIもOPの元のプログラムに依存する可能性がありますが、この機能は簡単で、理解しやすく、有益であり、OPの質問に到達します。最初の段落で述べたコアの問題。 –

0

random.choice()を使用しないでください。 random.shuffle()を代わりに使用して、(一意の)単語をランダムな順序で置き換え、繰り返しそのリストから取得します。これは、a)は、あなたがすべての単語を使用することを保証し、そしてb)任意のピックを繰り返さないでください:あなたは、ランダムな単語をいつでもちょうど使用し、その後、

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

と:

random_greeting = random.greetings.pop() 
関連する問題