第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

Python 中的循環(huán)和 choice() 函數(shù)

Python 中的循環(huán)和 choice() 函數(shù)

DIEA 2023-03-08 14:57:24
我是一名新手程序員,我試圖在我的書中為挑戰(zhàn)編寫代碼,其中包含一個循環(huán),該循環(huán)隨機獲取數(shù)字和/或字母以宣布彩票中獎?wù)摺N艺趪L試編寫代碼:從元組中取出一個未被拾取的隨機對象 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 個字符結(jié)果:$1M Winner[1, 'e']>>>為什么會這樣?我可以更改什么以使其選擇 4 個字符?
查看完整描述

3 回答

?
慕蓋茨4494581

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í)行您想要的操作。


查看完整回答
反對 回復(fù) 2023-03-08
?
GCT1015

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)


查看完整回答
反對 回復(fù) 2023-03-08
?
HUWWW

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

>>> 


查看完整回答
反對 回復(fù) 2023-03-08
  • 3 回答
  • 0 關(guān)注
  • 180 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號