随机列出单词而不重复 [英] Listing words randomly without repeating them
问题描述
我刚刚从《 Python绝对入门入门》一书中学习了如何在python中创建列表,并遇到了一个挑战,要求随机列出单词而不重复它们.我一直在尝试这样做,因为这本书没有给您答案.到目前为止,这是我的代码:
I just finished learning how to do lists in python from the book,Python Programming for the Absolute Beginner, and came across a challenge asking to list out words randomly without repeating them. I have been trying to do it since the book doesn't gives you the answer to it. So far this is my code:
WORDS = ("YOU","ARE","WHO","THINK")
for word in WORDS:
newword=random.choice(WORDS)
while newword==word is False:
newword=random.choice(WORDS)
word=newword
print(word)
很明显,由于单词在列表中重复出现,因此代码无法正常工作.
As obvious as it seems, the code didn't work out as the words repeat in lists.
推荐答案
您可以将shuffle用于列表而不是元组.
You could use shuffle with a list instead of a tuple.
import random
lst = ['WHO','YOU','THINK','ARE']
random.shuffle(lst)
for x in lst:
print x
请参见此Q/A 也在这里. 要将元组转换为列表,请执行以下操作: Q/A
See this Q/A here also. To convert a tuple to list: Q/A
如果坚持使用元组,则为完整代码:
The whole code if you insist on having a tuple:
import random
tuple = ('WHO','YOU','THINK','ARE')
lst = list(tuple)
random.shuffle(lst)
for x in lst:
print x
这篇关于随机列出单词而不重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!