3 回答
TA贡献1850条经验 获得超11个赞
实际上,它是选择四个字符。但是,当所选字符之一已在 中时lottery_winner,不会添加它。在这种情况下,您最终得到的总结果少于四个。
lenik 的回答是最实用的解决方案。但是,如果您对如何使用该choice函数进行操作的逻辑感到好奇,请记住,您需要在帽子出现重复时再次选择,或者您需要从帽子中消除选项当你去时。
选项 #1,每当获胜者重复时再试一次:
for i in range(4):
new_winner = False # Initially, we have not found a new winner yet.
while not new_winner: # Repeat the following as long as new_winner is false:
random = choice(lottery_1)
if random not in lottery_winner:
lottery_winner.append(pulled_number)
new_winner = True # We're done! The while loop won't run again.
# (The for loop will keep going, of course.)
选项 #2,每次都从列表中删除获胜者,这样他们就不会被再次选中:
for i in range(4):
random = choice(lottery_1)
lottery_winner.append(pulled_number)
lottery_1.remove(pulled_number) # Now it can't get chosen again.
请注意,remove()删除指定值的第一个实例,在值不唯一的情况下,这可能不会执行您想要的操作。
TA贡献1827条经验 获得超4个赞
import random
lottery_1 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e')
'''Instead of using the choice method which can randomly grab the same value,
i suggest that you use the sample method which ensures that you only get randomly unique values'''
# The k value represents the number of items that you want to get
lottery_winner = random.sample(lottery_1, k=4)
print('$1M Winner\n')
print(lottery_winner)
TA贡献1874条经验 获得超12个赞
这对我有用:
>>> import random
>>> lottery_1 = (1,2,3,4,5,6,7,8,9,'a','b','c','d','e')
>>> random.sample(lottery_1, 4)
[1, 7, 'a', 'e']
>>>
添加回答
举报