0

我正在研究我的第一个 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, 8, 6, 7, 5, 4, 4]

我该如何解决这个问题?如何防止新数据一遍又一遍地附加到同一个列表中,这使得列表无用?

提前致谢!

4

3 回答 3

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)]
于 2013-09-06T11:19:43.950 回答
0

Or even simplier would be the following

import random

def getRandom(start, end, quantity):
    return [random.choice(range(start, end)) for _ in range(quantity)]

print getRandom(0, 10, 10)
于 2013-10-11T23:12:03.310 回答
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)
于 2013-09-06T11:25:54.740 回答