慕仙森
在这种情况下,生成器会派上用场。编写一个带有无限循环的函数,该函数返回满足您条件的随机数,然后yield在调用该函数时使用语句一次返回一个这些值。这是一个例子。我添加了一些代码来检查输入参数,以确保在给定范围内有有效的结果。def random_not_power_of_2(rmin, rmax): # Returns a random number r such that rmin <= r < rmax, # and r is not a power of 2 from random import randint # Sanity check if rmin < 0: raise ValueError("rmin must be non-negative") if rmax <= rmin: raise ValueError("rmax must be greater than rmin") # Abort if the given range contains no valid numbers r = rmin isValid = False while r < rmax: if r == 0 or (r & (r-1) > 0): isValid = True break r += 1 if not isValid: raise ValueError("no valid numbers in this range") while True: r = randint(rmin, rmax) if r == 0 or (r & (r-1) > 0): yield rdef get_random_list(rmin, rmax, n): # Returns a list of n random numbers in the given range gen = random_not_power_of_2(rmin, rmax) return [next(gen) for i in range(n)]get_random_list(0,17,10)