For-Loop中不需要的随机迭代器

时间:2015-06-23 19:59:19

标签: python python-3.x

我试图创建一个函数,用于在两个其他值(startFrom和stopAt)之间生成一组值(numbersToChoose)但由于某种原因,在第二个for循环(第7行)中的迭代器(?),在此案例a似乎是随机生成的,即使我没有看到任何理由。

def chooseRandomNumbers(numbersToChoose, startFrom, stopAt):

 numbers = [(randrange(startFrom, stopAt))]  # initialize empty list of numbers

 for n in range(numbersToChoose-1):  # choose random number from 1 to 49 a total of 7 times
    x = randrange(startFrom, stopAt+1)
    for a in numbers:  # check for already existing elements in "numbers"
        if x == numbers[a]:  # if new random number already exists in "numbers" discard and run loop again
            n -= 1  # decreases n by 1 so a new (hopefully not already existing) number can be generated
        else:  # generated numbers does not exist in "numbers" yet
            numbers.append(x)  # appends randomly chosen number to list "numbers"

 return numbers  # returns said list "numbers"

非常感谢任何有关如何处理此问题的建议。 如果可能的话,请告诉我代码中的任何其他内容(刚刚启动python)。

1 个答案:

答案 0 :(得分:2)

检查列表中是否已生成号码的代码是错误的。 for a in numbers,在此循环中,您使用的是numbers[a],而a是列表的成员,但不是成员的索引。  使用in来测试数字是否在列表中:

来自随机导入randrange

def chooseRandomNumbers(numbersToChoose, startFrom, stopAt):
     numbers = []
     for n in range(numbersToChoose):
        x = randrange(startFrom, stopAt+1)
        if not x in numbers:
            numbers.append(x)
        else:
            n -= 1
     return numbers

或简单地说:

from random import sample
def chooseRandomNumbers(numbersToChoose, startFrom, stopAt):
    return sample(range(startFrom,stopAt+1),numbersToChoose)