2016-07-09 23 views
-2

遇到一些麻煩這個...新的隨機句話印在每次迭代

我能夠隨意創建一個句子與此代碼,但現在我要遍歷以使10個隨機句子。

import random, pprint 

#Create first list of elements 
elements1 = [] 

#Create second list of location descriptions 
prepositionList = [] 

#Create second list of elements (same as first) 
elements2 = [] 

#Randomly choose one entry from each list to make into sentence. 
randomSentence = (random.choice(elements1) + ' ' + random.choice(prepositionList) + ' ' + 
      random.choice(elements2)) 

print(randomSentence) 

我該如何打印10個不同的句子?

感謝

+1

把它放在一個循環中。 –

回答

1

重複一個循環內的代碼:

for i in range(<number of times to run>): 
    # Put here whatever you want to be executed 10 times 

循環語句使我們能夠執行語句或語句組多次

要了解更多有關循環:http://www.tutorialspoint.com/python/python_loops.htm

0

如何關於循環?這裏是你的方式代碼將如下:

random_sentences = [] 
for i in range(10): 
    random_sentence = (random.choice(elements1) + ' ' + 
         random.choice(prepositionList) + ' ' + random.choice(elements2)) 
    random_sentences.append(random_sentence) 
print random_sentences 

它的工作方式是,循環十次,每次創建一個random_sentence並將其添加到隨機句子的列表。