3 回答

TA貢獻1850條經(jīng)驗 獲得超11個贊
實際上,它是選擇四個字符。但是,當所選字符之一已在 中時lottery_winner,不會添加它。在這種情況下,您最終得到的總結(jié)果少于四個。
lenik 的回答是最實用的解決方案。但是,如果您對如何使用該choice函數(shù)進行操作的邏輯感到好奇,請記住,您需要在帽子出現(xiàn)重復(fù)時再次選擇,或者您需要從帽子中消除選項當你去時。
選項 #1,每當獲勝者重復(fù)時再試一次:
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()刪除指定值的第一個實例,在值不唯一的情況下,這可能不會執(zhí)行您想要的操作。

TA貢獻1827條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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']
>>>
添加回答
舉報