[英]How can I get unique random numbers?
I am wondering how I can get 6 unique random numbers. 我想知道如何获得6个唯一的随机数。 I have read about
random.sample
but in my case, I am generating 5 numbers 1-69 and the 6th number 1-26. 我已经阅读了有关
random.sample
但就我而言,我正在生成5个数字1-69和第6个数字1-26。 I need all 6 to be unique. 我需要所有6个都是唯一的。 This is my code.
这是我的代码。
import tkinter
import random
class Lottery_GUI:
def __init__(self):
self.main_window = tkinter.Tk()
self.main_window.geometry('500x100')
self.main_window.title('Lottery Number Generator')
self.frame1 = tkinter.Frame(self.main_window)
self.frame2 = tkinter.Frame(self.main_window)
self.frame1.pack()
self.frame2.pack()
self.list1 = tkinter.IntVar()
#Lottery label
self.Lottery_label = tkinter.Label(self.frame1,\
text = 'Welcome to the Lottery Generator')
self.Lottery_label.pack()
#Button to generate the numbers
self.Lottery_button = tkinter.Button(self.frame2,\
text = 'Click to Generate Numbers',\
command = self.Generate_Num)
self.Lottery_button.pack()
#Display the random numbers
self.num_entry = tkinter.Entry(self.frame1, textvariable = self.list1,\
width = 20, fg = 'blue', justify = 'center')
self.num_entry.pack(side = 'bottom')
tkinter.mainloop()
def Generate_Num(self):
a = random.randint(1,69)
b = random.randint(1,69)
c = random.randint(1,69)
d = random.randint(1,69)
e = random.randint(1,69)
f = random.randint(1,26)
list = [a,b,c,d,e,f]
list.sort()
self.list1.set(list)
my_lottery = Lottery_GUI()
I have tried doing random.sample(range(1,70, 5)
in the function Generate_Num
, but the problem is I can't check the 6th number which only ranges from 1-26. 我试过在函数
Generate_Num
执行random.sample(range(1,70, 5)
,但是问题是我无法检查第6个数字,该数字仅在1-26范围内。
You can sample without replacement. 您可以取样而无需更换。 See
np.random.choice
参见
np.random.choice
This should work: 这应该工作:
a = np.random.choice(26, 1)
np.random.choice(np.delete(np.arange(69), a),5, replace=False)
a
is your 6th element. a
是您的第六元素。
Instead of using randint
, use sample
and choice
with filtering: 而不是使用
randint
,而是使用带有过滤的sample
和choice
:
import random
first_five = random.sample(range(70), 5)
last = random.choice([number for number in range(27) if number not in first_five])
numbers = first_five + [last]
print(numbers)
Output: 输出:
[53, 52, 9, 0, 8, 21]
You can perform sorting and other stuff later. 您可以稍后执行排序和其他操作。
Also, avoid naming your variable list
as that shadows (hides) the builtin. 另外,避免命名变量
list
因为它会隐藏(隐藏)内置函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.