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 个随机字母?
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 个随机字母?
我能想到的最简单的方法是随机化整个列表并根据需要获取尽可能多的元素:
>>> 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']
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']
此函数从传递的字符串列表中返回一个随机字符串。
def getRandomWord(wordList):
wordIndex = random.randint(0, len(wordList) - 1)
return wordList[wordIndex]
这个函数使用上面的 def 得到一个随机词。
secretword = Randomword(hangmanwords)