Python 中的循环和 choice() 函数

我是一名新手程序员,我试图在我的书中为挑战编写代码,其中包含一个循环,该循环随机获取数字和/或字母以宣布彩票中奖者。

我正在尝试编写代码:

  • 从元组中取出一个未被拾取的随机对象 4 次

  • 将每个对象存储在列表中

  • 打印清单

from random import choice #Import choice() function from the random module


lottery_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 个字符?


DIEA
浏览 141回答 3
3回答

慕盖茨4494581

实际上,它是选择四个字符。但是,当所选字符之一已在 中时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()删除指定值的第一个实例,在值不唯一的情况下,这可能不会执行您想要的操作。

GCT1015

import randomlottery_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 getlottery_winner = random.sample(lottery_1, k=4)print('$1M Winner\n')print(lottery_winner)

HUWWW

这对我有用:>>> 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']>>> 
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python