我正在开发我的第一个OOP项目,它是一个随机数生成器,可以在给定范围内生成许多随机数:
import random
import math
resList=[]
class randomInRange:
def getRandom(self, start, end, quantity):
for i in range(quantity):
selList = range(start, end)
resNum = random.choice(selList)
resList.append(resNum)
return (resList)
RR=randomInRange()
然后,我会在Python Shell中输入:
(RR.getRandom(0,10,10))
它会给出类似的东西:[2,2,1,4,8,1,0,7,4,5] 但是,如果我再次调用该函数,它会追加新生成的函数 数字到同一个列表。所以它想要这样的东西:[2,2,1,4,8,1,0,7,4,5,4,5,3,1,5,6,7,5,4,4] < / p>
我如何解决这个问题?如何防止新数据一遍又一遍地附加到同一列表中,这使得列表无用?
提前致谢!
答案 0 :(得分:2)
那是因为resList
是一个全局变量,在调用randomInRange
时你永远不会擦除它的内容。您应该只在函数中创建列表:
class randomInRange:
def getRandom(self, start, end, quantity):
resList = []
for i in range(quantity):
selList = range(start, end)
resNum = random.choice(selList)
resList.append(resNum)
return (resList)
请注意,您的功能也可以用列表推导替换:
def getRandom(self, start, end, quantity):
temp = range(start, end)
return [random.choice(temp) for _ in range(quantity)]
答案 1 :(得分:0)
import random
import math
resList=[]
class randomInRange:
def getRandom(self, start, end, quantity):
for i in range(quantity):
selList = range(start, end)
resNum = random.choice(selList)
if resNum not in resList:
resList.append(resNum)
return (resList)
RR=randomInRange()
print RR.getRandom(0,10,10)
答案 2 :(得分:0)
甚至更简单的是以下
import random
def getRandom(start, end, quantity):
return [random.choice(range(start, end)) for _ in range(quantity)]
print getRandom(0, 10, 10)