我正在使用Python及其标准库函数random.choice
。我只是想知道,有没有办法得不到相同的结果,例如没有得到"Strawberry"
两次。我已经尝试了许多方法,但没有提出任何建议。
我已经包含了我的代码:
#Random selection for for doughnuts
import random
from tkinter import *
Doughnuts = ['Strawberry', 'Apple Cinnamon',
'Blueberry Blaster', 'Custard', 'Sugar', ...]
def RandomDough():
for i in range(6):
print (random.choice(Doughnuts))
app=Tk()
app.title('Your tkinter app')
app.geometry('450x100+200+100')
b1=Button(app, text='Random Special', width = 20, command=RandomDough)
b1.pack(side='right')
app.mainloop()
我甚至尝试使用random.sample
,但我想不出如何将int
数字转换为实际的单词"Strawberry"
:
#Random selection for for doughnuts
import random
from tkinter import *
def RandomDough():
Doughnuts = random.sample(range(1, 8), 6)
print (Doughnuts)
app=Tk()
app.title('Your tkinter app')
app.geometry('700x200+200+100')
b1=Button(app,text='Random Special',width = 20,height = 20,command=RandomDough)
b1.pack(side ='right')
app.mainloop()
答案 0 :(得分:5)
只需将Doughnuts
列表传递给random.sample()
;不要使用指数:
Doughnuts = ['Strawberry ','Apple Cinnamon ','Blueberry Blaster ','Custard ','Sugar']
for choice in random.sample(Doughnuts, 6):
print(choice)
答案 1 :(得分:3)
随机播放它们,然后使用或迭代切片...:
from random import shuffle
Doughnuts = ['Strawberry ','Apple Cinnamon ','Blueberry Blaster ','Custard ','Sugar']
shuffle(Doughnuts)
for doughnut in Doughnuts[:6]:
print doughnut # or whatever
这可以适用于一次选择一个独特的dougnuts,例如:
shuffle(Doughnuts)
items = iter(Doughnuts)
doughnut = next(items) # get 1
# .... other code
another_doughnut = next(items)