检查先前循环中是否存在随机值

时间:2016-10-11 02:07:39

标签: python loops random

我试图为每个循环生成一个随机值并将其保存到变量minimum WHILE检查是否在之前的一个循环之前已经生成了该数字。

listQ基本上包含从文件中随机选择的 6行。这些行是从1max_line之间选择的(基本上比max_line值小6步)。因此,我必须生成一个乘数为6的数字非常重要。

for x in range(0, 10):
    minimum = random.randrange(0, max_line,6)
    maximum = minimum+6
    listQ = listQ[minimum:maximum]

有点卡在这里。列表可能?

1 个答案:

答案 0 :(得分:1)

保留所有先前值的列表,并检查每次后续迭代。

# sets have faster "val in set?" checks than lists
# do this once, somewhere in your program
previous_vals = set()

# other stuff here, including main program loop
for x in range(0, 10):
    # find a unique, new random number while 
    # limiting number of tries to prevent infinite looping
    number_of_tries = 0
    MAX_TRIES = 10
    generating_random = true
    while generating_random:    
        minimum = random.randrange(0, max_line,6)
        if minimum not in previous_vals:
            previous_vals.add(minimum)
            generating_random = false
        number_of_tries += 1
        if number_of_tries == MAX_TRIES:
            raise RunTimeError("Maximum number of random tries reached!")

    maximum = minimum+6
    listQ = listQ[minimum:maximum]

如果您想修改示例,请注意there are other functions for set than add

我还添加了最多尝试次数,以防止您的代码陷入无限循环,因为我对输入数据一无所知,无法知道进入这种情况的可能性。