Python 掷骰子程序-类型错误:列表索引必须是整数,而不是列表
我正在写一个程序,可以掷任意数量的骰子,任意边,任意次数。我被困在我的函数中,它掷骰子数次,然后用骰子替换列表中的零。我在Python 掷骰子程序-类型错误:列表索引必须是整数,而不是列表,python,list,python-3.x,dice,Python,List,Python 3.x,Dice,我正在写一个程序,可以掷任意数量的骰子,任意边,任意次数。我被困在我的函数中,它掷骰子数次,然后用骰子替换列表中的零。我在rolls[rv]+=1上不断得到一个错误: TypeError:列表索引必须是整数,而不是列表 我发送给rolls的ctrList函数确实返回了一个列表,我在rollSim函数中尝试将该列表更改为int或str,但似乎没有任何效果。也许我处理这个问题的方式不对?以下是迄今为止我在该领域的代码: numDice=int(input("How many dice do you
rolls[rv]+=1上不断得到一个错误:
TypeError:列表索引必须是整数,而不是列表
我发送给rolls的ctrList
函数确实返回了一个列表,我在rollSim
函数中尝试将该列表更改为int
或str
,但似乎没有任何效果。也许我处理这个问题的方式不对?以下是迄今为止我在该领域的代码:
numDice=int(input("How many dice do you want to roll? "))
numSides=int(input("How many Sides does each have? "))
numRolls=int(input("How many times do you want to roll the dice? "))
def ctrList(numSides, numDice): #Function that seeds list with all zeros
L=[]
ctr=0
possible= ((numSides * numDice)+1)
for p in range (possible):
ctr+=1
L.append(0)
return L
def rollSim(numDice, numSides, numRolls, rollDice):
rolls=ctrList(numSides, numDice)
for i in range (numRolls):
rv= rollDice(numDice, numSides )
rolls[rv]+=1 #where I keep on getting the error at :(
return rolls
def rollDice(numDice, numSides ): #Function that rolls dice
L=[]
ctr=0
for dice in range (numDice):
L.append (random.randint(1, numSides))
ctr+=1
return L
这似乎不是:
for i in range (numRolls):
rv= rollDice(numDice, numSides )
rolls[rv]+=1 #where I keep on getting the error at :(
你需要:
for i in range (numRolls):
rv = rollDice(numDice, numSides)
for dice in rv:
rolls[dice] += 1
您的rollDice
返回numDice
骰子的结果(一个列表
)。然后尝试用另一个列表索引rolls
列表,这没有任何意义(这正是错误所说的)
您还可以更改该方法,使其对于一个骰子仅返回一个结果:
def rollDice(numSides):
return random.randint(1, numSides)
因此,您的计数代码版本将起作用。取决于您想要什么。您的rollDice函数返回一个列表,因此当您执行此操作时
rv = rollDice(numDice, numSides)
将列表指定给rv。您不能从那里执行rolls[rv],rv需要是int。您是否尝试过将rv的值直接打印到命令行?rv似乎不是整数,因此python无法将其用作索引。谢谢!这正是我需要它做的!