为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 140 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信