随机 gen() 在列表中选择一个重复的数字,与 33、33 相同的数字。我想从数字 [0.99] 中获得不同的列表。应该使用什么方法来修复错误?
回答1
https://docs.python.org/3/library/random.html 库在 https://docs.python.org/3/library/random.html#random.sample 中为您提供了一个函数
>>> import random
>>> random.sample(range(100),5)
[86, 27, 78, 74, 57]
>>>
如果你只想要一个数字,你可以使用 https://docs.python.org/3/library/random.html#random.choice 或 https://docs.python.org/3/library/random.html#random.randint
>>> random.choice(range(100))
23
>>> random.randint(0,99)
77
>>>
回答2
这是一个使用 https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html 的 numpy
解决方案。设置标志 replace=False
可以避免重复。
import numpy as np
draws = 6
np.random.choice(range(0,100), draws, replace=False)
除了传递 range(100)
,您还可以传递 100,这将返回 0-99 之间的数字。
输出:
array([76, 74, 2, 37, 96, 41])
回答3
# import random (library to generate random numbers)
import random
# declare a variable l_number (lottery number) using the function random.choice()
l_number = random.choice(range(0, 100))
# print the lottery number
print(l_number)