flink = open("C:/python27/2of12inf.txt", "rU")
words = [ ]
for eachline in flink :
words += [eachline.strip()]
flink.close()
print "%d words read" % len(words)
return words
如何从此列表中选择6个随机字母?
答案 0 :(得分:2)
我能想到的最简单的方法是随机化整个列表并根据需要选择尽可能多的元素:
>>> words = "one two three four five six seven eight nine ten".split()
>>> import random
>>> random.shuffle(words)
>>> words[:6]
['two', 'five', 'six', 'seven', 'four', 'one']
>>> random.shuffle(words)
>>> words[:6]
['five', 'seven', 'nine', 'three', 'four', 'eight']
答案 1 :(得分:0)
random.sample更清洁
>>>words = "one two three four five six seven eight nine ten".split()
>>>import random
>>>random.sample(words, 6)
['six', 'seven', 'eight', 'nine', 'three', 'ten']
>>>random.sample(words, 6)
['three', 'five', 'four', 'six', 'one', 'ten']
>>>random.sample(words, 6)
['ten', 'five', 'two', 'nine', 'seven', 'eight']
答案 2 :(得分:0)
此函数从传递的字符串列表中返回一个随机字符串。
def getRandomWord(wordList):
wordIndex = random.randint(0, len(wordList) - 1)
return wordList[wordIndex]
此函数使用上面的def获取一个随机单词。
secretword = Randomword(hangmanwords)