我想知道如何获得6个唯一的随机数。我已经读过random.sample
,但就我而言,我正在生成5个数字1-69和第6个数字1-26。我需要所有6个都是唯一的。这是我的代码。
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()
我尝试在函数random.sample(range(1,70, 5)
中进行Generate_Num
,但是问题是我无法检查第6个仅在1-26之间的数字。
答案 0 :(得分:2)
您可以取样而无需更换。参见np.random.choice
这应该有效:
a = np.random.choice(26, 1)
np.random.choice(np.delete(np.arange(69), a),5, replace=False)
a
是您的第六个要素。
答案 1 :(得分:2)
使用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)
输出:
[53, 52, 9, 0, 8, 21]
稍后您可以执行排序和其他操作。
此外,避免命名变量list
,因为它会遮盖(隐藏)内置函数。