我想生成一个随机数,并且该随机数应该是唯一的,这意味着它不应重复或再次生成。我尝试制作一个列表,在每个迭代中都附加一个列表,并检查列表中是否已经存在该列表。如果列表中存在该数字,则不会附加该数字。但是我认为这不是一种有效的方法。所以,请帮我。
import random
#an empty list to append randomly generated numbers
empty = []
while True:
#checking from range 500 to 510
number = random.randrange(500, 510)
if number not in empty:
empty.append(number)
else:
pass
#breaking the loop if the length of the numbers is 9
if len(empty) == 9:
break
print("Final list --> " + str(empty))
您可以通过random.sample
以下方法从给定的池中获取给定数量的非重复元素的列表:
>>> random.sample(range(500, 510), 9)
[500, 501, 503, 502, 505, 507, 508, 506, 504]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句