循环遍历类实例中的属性?
我正在尝试模拟棒球游戏,以了解有关Python和编程的更多信息...我遇到了一个有趣的学习点...并且想知道是否有人可以解释这个错误...
import random
rosterHome = []
rosterAway = []
class Player:
def __init__(self, number, battingAverage):
self.number = number
self.battingAverage = battingAverage
class Game:
def __init__(self):
self.inning = 0
self.homeScore = 0
self.awayScore = 0
self.outs = 0
def createStats():
for i in range(40):
stats = random.random()
x = Player(i, stats)
rosterHome.append(x)
for y in range(40):
stats = random.random()
y = Player(i, stats)
rosterAway.append(y)
def startGame():
Game.createStats()
Game.inning = 0
Game.homeScore = 0
Game.awayScore = 0
Game.outs = 0
Game.playInning()
def playInning():
totalHits = 0
if Game.inning >= 10:
print('Game is Over')
return
while Game.outs < 3:
for i in rosterHome:
x = rosterHome[i]
if x.battingAverage > random.random():
totalHits += 1
player += 1
print('batter ', player, ' got a hit')
else:
Game.outs += 1
player += 1
print('batter ', player, ' got out')
print('there are ', Game.outs, ' outs.')
Game.startGame()
x = Rosterhome [i] TypeError:列表索引必须是整数或切片,而不是播放器
I am trying to simulate a baseball game to learn more about python and programming in general... I ran into an interesting learning point in programing... and was wondering if someone could explain this error...
import random
rosterHome = []
rosterAway = []
class Player:
def __init__(self, number, battingAverage):
self.number = number
self.battingAverage = battingAverage
class Game:
def __init__(self):
self.inning = 0
self.homeScore = 0
self.awayScore = 0
self.outs = 0
def createStats():
for i in range(40):
stats = random.random()
x = Player(i, stats)
rosterHome.append(x)
for y in range(40):
stats = random.random()
y = Player(i, stats)
rosterAway.append(y)
def startGame():
Game.createStats()
Game.inning = 0
Game.homeScore = 0
Game.awayScore = 0
Game.outs = 0
Game.playInning()
def playInning():
totalHits = 0
if Game.inning >= 10:
print('Game is Over')
return
while Game.outs < 3:
for i in rosterHome:
x = rosterHome[i]
if x.battingAverage > random.random():
totalHits += 1
player += 1
print('batter ', player, ' got a hit')
else:
Game.outs += 1
player += 1
print('batter ', player, ' got out')
print('there are ', Game.outs, ' outs.')
Game.startGame()
x = rosterHome[i]
TypeError: list indices must be integers or slices, not Player
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
TLDR:
列表索引必须是整数或切片
解释器说“嘿,我看到您正在尝试通过索引访问列表中的项目,但索引应该是
integer
类型,但是,您传递了Player 类型的值
”在Python和大多数编程语言中,要引用列表/数组中的项目,一种方法是通过索引。列表是零索引的,因此第一个项目的索引为 0,第二个项目的索引为 1,依此类推。
给定一个数组
但是在您的情况下,如果我们从错误发生的位置追溯到这里:
您想问,
i
的值是多少?此行上方是一个 for 循环,i
表示名为rosterHome
的列表中的每个值。那么rosterHome
到底是什么?向上移动到填充
rosterHome
列表的createStats
方法,我们看到您正在将Player
的实例推送到rosterHome
列表。所以 rosterHome 实际上不是一个数字列表,而是一个
Player
实例列表。您可能想要检查并重试,也许可以访问 Player 对象的 number 属性。TLDR:
List indices must be integers or slices
The interpreter says "Hey, I see you're trying to access an item in a List by its index, but indices should be of type
integer
, however, you passed a value of typePlayer
"In Python and most programming languages, to reference an item in a List/Array, one way would be by index. Lists are zero-indexed, so the first item is of index 0, the second index 1, and so on.
Given an Array
However in your case, if we trace back up from where the error occurred, right here:
You want to ask, what is the value of
i
? above this line is a for loop, andi
represents each value in a list calledrosterHome
. So what the heck is inrosterHome
anyways?Moving up into your
createStats
method where you populated therosterHome
list, we see that you're pushing an instance ofPlayer
into therosterHome
list.So rosterHome really isn't a list of numbers but instead a list of
Player
instances. You might want to review and try again, maybe accessing the number property of the Player object instead.发生错误的原因是
rosterHome
是Player
类的实例列表,因此当您迭代该列表时 (for i in rosterHome
) element 将是该类的一个实例(i
是一个Player
)。如果您想访问每个玩家的号码,则必须访问Player
实例的属性number
,但实际上您似乎想要找到玩家实例。这意味着,您甚至不需要查找表中的值,只需使用 for 循环的值即可。我将使用不同的变量命名来提高可读性:这部分答案认为您实际上希望满足这两个要求(出局数和迭代玩家一次):
The error happens because
rosterHome
is a list of instances of thePlayer
class, so when you iterate on the list (for i in rosterHome
) each element will be an instance of said class (i
is aPlayer
). If you want to access the number of each player you'll have to access the attributenumber
of yourPlayer
instances, but it seems like actually you want to find the player instance. This means, you don't even need to lookup the value in the table, just use the value of the for loop. I'll use a different naming of variables to improve readability:This part of the answer considers that you actually want to meet both requirements (number of outs and iterate players once):