为什么add函数会中断while循环



我开发了一个函数all_dice((,它应该取一个选择值,表示用户想要投掷多少骰子,然后投掷相应数量的骰子。我想把每个roll_((变量存储在一个空集thisset=set((中,这样只需返回并打印all_dice((就可以得到我的最终分数。但我得到的只是一个价值。既定的想法似乎拦截了while循环。F.e当我设置choice==5时,这个集合只包含{4}。如果它能按预期工作,函数应该从choice=5开始,得到一个roll_((数字,将其存储在thisset{}中,然后按choice=choice-1倒计时,转到choice==4,依此类推。因此,当choice=5时,我希望thisset{}内有5个值。

如果没有thisset.add((函数,all_dice((函数将按预期工作——倒计时选择并产生相应的值。

有人能告诉我为什么while循环会被拦截/问题出在哪里吗?

这是我的第一个节目,所以请对我温柔一点-谢谢你的帮助!

#function to role many dice 
import random
choice =5
print("choice is:",choice)
def all_dice(choice):
while choice>=1:
thisset=set()
if choice==1:
roll_1=random.randint(1,6)
thisset.add(roll_1)
choice=choice-1
if choice==2:
roll_2=random.randint(1,6)
thisset.add(roll_2)
choice=choice-1
if choice==3:
roll_3=random.randint(1,6)
thisset.add(roll_3)
choice=choice-1
if choice==4:
roll_4=random.randint(1,6)
thisset.add(roll_4)
choice=choice-1
if choice==5:
roll_5=random.randint(1,6)
thisset.add(roll_5)
choice=choice-1
return thisset
print(all_dice(choice))

每次循环都要清除集合,因此会丢失以前的项目。在循环之前,您只需要初始化它一次。(由于某些原因,这种类型的错误在初学者中非常常见。(

您不需要所有这些不同的变量或if语句,因为它们都做相同的事情。

def all_dice(choice):
thisset = set()
for _ in range(choice):
thisset.add(random.randint(1, 6))
return thisset

我不知道你为什么要用一套来掷多个骰子。一个集合不能有重复的,所以如果多次滚动相同的数字,该集合将只包含其中一个。如果你想掷5个骰子,你通常会用一个列表来容纳所有的骰子。如果你只关心总和,你根本不需要保存所有不同的卷,只需将它们添加到一个总变量中即可。

这是我能想到的最Python的方法。我不建议使用set(),除非你永远不想在你的数据中重复:

import random
def roll_dice(rolls=1):
return [random.randint(1, 6) for roll in range(rolls)]
roll_dice(5)

或者另一种方法:

import random
roll_dice = lambda rolls: [random.randint(1, 6) for roll in range(rolls)]
roll_dice(5)

输出:

[2, 1, 1, 5, 1]
#function to role many dice 
import random
choice =5
print("choice is:",choice)
def all_dice(choice):
thisset = [] 
while choice>=1:
if choice==1:
roll_1=random.randint(1,6)
thisset.append(roll_1)
choice=choice-1
if choice==2:
roll_2=random.randint(1,6)
thisset.append(roll_2)
choice=choice-1
if choice==3:
roll_3=random.randint(1,6)
thisset.append(roll_3)
choice=choice-1
if choice==4:
roll_4=random.randint(1,6)
thisset.append(roll_4)
choice=choice-1
if choice==5:
roll_5=random.randint(1,6)
thisset.append(roll_5)
choice=choice-1
return thisset
print(all_dice(choice))

我得到的样本输出是:-

[3, 1, 6, 5, 2]

set不能有重复项,所以我使用了list

最新更新