![](/img/trans.png)
[英]How to limit the number of times a specific random number is generated python
[英]Use the same Random Generated Number Several Times
我正在编写一个代码,其中用户输入一个句子,一次输入一个单词。 当他们键入'exit'时,代码将返回“您的原始句子为句子。单词编号(生成随机数)为(与该编号对应的单词)”。
例如,句子是“这是一个很酷的代码”,它将返回“您的原始句子是这是一个很酷的代码。单词3是一个。
现在,我的代码获得了两个不同的随机数和单词,因此就像“单词2是这个”或类似的东西。 我应该如何解决并使其正常工作?
print ('Think of a sentence')
print ('Type the sentence one word at a time pressing enter after each word')
print ("When you have finished the sentence enter 'exit'")
print ('')
sentence = []
while True:
word = input('')
print ('Accepted', word)
if word == 'exit':
print ('')
print ('Your original sentence was')
outputString = " ".join(sentence)
print (outputString)
wordCount = len(outputString.split())
pleaseWork = (random.randint(0,wordCount))
print('Word number ',pleaseWork,' is ', (sentence[pleaseWork]))
break
sentence.append(word)
你快到了!
当您这样做时:
pleaseWork = (random.randint(0,wordCount))
您得到的数字(在pleaseWork
变量中)介于零和len(outputString)
,该数字(由于outputString
是字符串)将为您提供outputString
的字符数。
试试看:
>>> len("Hello, my name is BorrajaX")
26
但是,您真正想要的是在0
和sentence
列表中项目数之间的随机索引,对吗? 因为当您执行以下操作: sentence[pleaseWork]
您正在将pleaseWork
用作sentence
列表的索引,而不是outputString
字符串的索引。
所以,您在这里做什么:
wordCount = int(len(outputString))
pleaseWork = (random.randint(0,wordCount))
print('Word number ',pleaseWork,' is ', (sentence[pleaseWork]))
可以缩短为:
pleaseWork = random.randint(0, len(outputString))
print('Word number ',pleaseWork,' is ', (sentence[pleaseWork]))
你现在看到了吗? pleaseWork
包含一个介于0
和outputString
长度之间的数字。 但是,您正在使用该数字访问您的列表sentence
。 如果outputString
有100个字符,而sentence
只有三项,会发生什么情况? 好吧...您很可能在random.randint
调用中获得大于2
的整数。 假设您得到... 50
...当您尝试访问包含第三个项目的列表中的第50个项目时会发生什么?
>>> [1, 2, 3][50]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
因此,您应该做的是将该randint
的范围更改为sentence
列表中的项目数:
wordCount = int(len(sentence))
pleaseWork = (random.randint(0, wordCount))
完整示例:
def sentenceSplit():
print ('Think of a sentence')
print ('Type the sentence one word at a time pressing enter after each word')
print ("When you have finished the sentence enter 'exit'")
print ('')
sentence = []
while True:
word = raw_input('')
print ('Accepted', word)
if word == 'exit':
print ('')
print ('Your original sentence was')
outputString = " ".join(sentence)
print (outputString)
wordCount = int(len(sentence))
pleaseWork = (random.randint(0, wordCount))
print('Word number ', pleaseWork, ' is ', (sentence[pleaseWork]))
break
sentence.append(word)
您正在使用句子中的字符数来为句子中的单词生成索引。 将wordCount = int(len(outputString))
更改为wordCount = len(sentence) - 1
以获取适当的索引。
由于您只调用过randint
因此不会得到两个不同的随机数或单词。 问题是两件事:
wordCount
当前是字符串中的字符数。 请改用len(sentence)
。 randint
包含其上限(与不包括该range
不同,因此您不必考虑这样的事情),这意味着random.randint(0,wordCount)
有时会返回wordCount
,因此pleaseWork == wordCount == len(sentence)
(假设您执行上述操作)是可能的,并且sentence[len(sentence)]
必然会引发错误。 使用random.randint(0,wordCount-1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.