为每次迭代打印新的随机句子

时间:2016-07-09 23:02:38

标签: python

遇到这个问题...

我能够使用此代码随机创建一个句子,但现在我想迭代生成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个不同的句子?

由于

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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并将其添加到随机句子列表中。

相关问题