我正在用Python构建老虎机模拟器。我已将卷轴设置如下:
Reels = [[10,9,4,5,7,4,9,2,6,7,3,4,9,3,4,9,6,5,4,11,8,9,11,2,4,1,9,10,4,9,10,6,4,9,1,5,4,9,1,10,3,8,6,4,9,1,8],
[4,3,5,4,3,5,2,8,4,1,8,10,1,2,9,8,11,2,8,5,6,11,3,4,2,8,4,7,6,10,8,7,9,4,1,6,8,4,2,9,8,3,5,4,10,8],
[1,9,4,2,5,1,6,9,2,5,9,2,10,9,4,8,9,11,2,5,8,9,10,4,1,10,9,2,10,5,9,7,5,6,8,9,7,3,10,6,2,9,5,8,3,1,10,3],
[8,10,3,8,7,3,9,8,10,11,3,10,9,6,8,10,11,6,5,3,8,1,4,9,5,8,1,4,3,8,1,5,9,10,8,3,9,4,3,8,9,4,6,11,3,8,9,7,10,11],
[4,11,1,6,3,9,5,10,9,5,8,11,10,3,1,4,10,3,9,4,7,3,9,10,4,3,1,5,10,6,5,8,4,6,9,1,5,10,8,9,5,4,6,8,9,4,8,5,7,9]]
现在,我需要从1到5遍历它们,并构建3X5矩阵。我想从产生一个随机数开始,该随机数确定该转轴上的停止位置。该值将是该卷轴上的中间值。然后,我需要添加顶部和底部的值(但必须考虑中间编号可能位于卷轴条的开头或结尾。我在
if StopValue == Reels[i][len(Reels[i])]:
上收到错误“列表索引超出范围”线:def spin():
SpinValues = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
for i, object in enumerate(Reels):
length = len(Reels[i])
StopValue = random.randint(0,length)
SpinValues[i][1] = Reels[i][StopValue]
if StopValue == 0:
SpinValues[i][0] = Reels[i][len(Reels[i])]
else:
SpinValues[i][0] = Reels[i][StopValue - 1]
if StopValue == Reels[i][len(Reels[i])]:
SpinValues[i][2] = Reels[i][0]
else:
SpinValues[i][2] = Reels[i][StopValue +1]
print(SpinValues)
spin()
最初,我认为我可以仅使用“ for i in reels”来做到这一点,但是我在这里阅读了一篇建议使用“ for index,enumerate(Reels)中的对象”方法的文章。
最佳答案
len(Reels[i])
不是Reels[i]
的有效索引。最后一个有效索引是len(Reels[i]) - 1
关于python - Python:如何枚举列表列表并使用该列表的长度查找值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55069100/