我正在尝试制作一个彩票机,生成一个列表,其中包含 7 个中奖号码和 3 个奖金号码,从 1-34。我希望奖金号码永远不会选择与中奖号码相同的号码。
winning_numbers = random.sample(range(1, 34), 7)
bonus_numbers = random.sample(range(1, 34), 3)
是否有任何命令/代码可以排除先前列表中已选择的数字?
最佳答案
随机
解
如果你只想使用random
模块,你可以使用:
import random
nums = random.sample(range(1,35), 10)
winning_numbers = nums[:7]
bonus_numbers = nums[7:]
>>> winning_numbers
[2, 23, 29, 34, 26, 16, 13]
>>> bonus_numbers
[8, 4, 19]
因为 random.sample
是“用于无放回的随机抽样”。 (转自docs)
numpy
解决方案
您还可以使用 numpy
,因为 numpy.random.choice
有一个 replace
参数,您可以将其设置为 false
。 (我个人是一个粉丝或使用 numpy
作为随机数,因为它在更复杂的任务中比 random
提供了更多的灵 active )
import numpy as np
nums = np.random.choice(range(1,35), 10, replace=False)
winning_numbers = nums[:7]
bonus_numbers = nums[7:]
>>> winning_numbers
array([27, 4, 17, 30, 32, 21, 23])
>>> bonus_numbers
array([15, 13, 18])
关于python - 我如何制作一个随机唯一数字列表,避免使用已经存在的随机唯一数字列表中的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49783082/