亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python 中的循環和 choice() 函數

Python 中的循環和 choice() 函數

DIEA 2023-03-08 14:57:24
我是一名新手程序員,我試圖在我的書中為挑戰編寫代碼,其中包含一個循環,該循環隨機獲取數字和/或字母以宣布彩票中獎者。我正在嘗試編寫代碼:從元組中取出一個未被拾取的隨機對象 4 次將每個對象存儲在列表中打印清單from random import choice #Import choice() function from the random modulelottery_1 = (1,2,3,4,5,6,7,8,9,'a','b','c','d','e')lottery_winner = []for i in range(4): #Takes 4 random numbers and/or letters    random = choice(lottery_1)    if random not in lottery_winner:        lottery_winner.append(pulled_number)print('$1M Winner\n')print(lottery_winner)有時它只選擇 2 個字符結果:$1M Winner[1, 'e']>>>為什么會這樣?我可以更改什么以使其選擇 4 個字符?
查看完整描述

3 回答

?
慕蓋茨4494581

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()刪除指定值的第一個實例,在值不唯一的情況下,這可能不會執行您想要的操作。


查看完整回答
反對 回復 2023-03-08
?
GCT1015

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)


查看完整回答
反對 回復 2023-03-08
?
HUWWW

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']

>>> 


查看完整回答
反對 回復 2023-03-08
  • 3 回答
  • 0 關注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號