循环遍历类实例中的属性?

发布于 2025-01-19 00:21:03 字数 1623 浏览 0 评论 0原文

我正在尝试模拟棒球游戏,以了解有关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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

国际总奸 2025-01-26 00:21:03

TLDR
列表索引必须是整数或切片
解释器说“嘿,我看到您正在尝试通过索引访问列表中的项目,但索引应该是 integer 类型,但是,您传递了 Player 类型的值

在Python和大多数编程语言中,要引用列表/数组中的项目,一种方法是通过索引。列表是零索引的,因此第一个项目的索引为 0,第二个项目的索引为 1,依此类推。

给定一个数组

my_array = ["bread", "foo", "bar"]

my_array[0] # would give you "bread"
my_array[1] # would give you "foo"
my_array[2] # would give you "bar"

但是在您的情况下,如果我们从错误发生的位置追溯到这里:

x = rosterHome[i] 

您想问,i 的值是多少?此行上方是一个 for 循环,i 表示名为 rosterHome 的列表中的每个值。那么 rosterHome 到底是什么?

向上移动到填充 rosterHome 列表的 createStats 方法,我们看到您正在将 Player 的实例推送到 rosterHome 列表。

x = Player(i, stats) 
rosterHome.append(x)

所以 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 type Player"

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

my_array = ["bread", "foo", "bar"]

my_array[0] # would give you "bread"
my_array[1] # would give you "foo"
my_array[2] # would give you "bar"

However in your case, if we trace back up from where the error occurred, right here:

x = rosterHome[i] 

You want to ask, what is the value of i? above this line is a for loop, and i represents each value in a list called rosterHome. So what the heck is in rosterHome anyways?

Moving up into your createStats method where you populated the rosterHome list, we see that you're pushing an instance of Player into the rosterHome list.

x = Player(i, stats) 
rosterHome.append(x)

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.

冬天的雪花 2025-01-26 00:21:03

发生错误的原因是 rosterHomePlayer 类的实例列表,因此当您迭代该列表时 (for i in rosterHome) element 将是该类的一个实例(i 是一个 Player)。如果您想访问每个玩家的号码,则必须访问 Player 实例的属性 number,但实际上您似乎想要找到玩家实例。这意味着,您甚至不需要查找表中的值,只需使用 for 循环的值即可。我将使用不同的变量命名来提高可读性:

while Game.outs < 3:
    for player in rosterHome:
        # x wanted to access a player, but we don't need to do that actually
        if player.battingAverage > random.random():
            # ...
        else:
            # ...

这部分答案认为您实际上希望满足这两个要求(出局数和迭代玩家一次):

player_index = 0
while Game.outs < 3 and player_index< len(rosterHome):
    player = rosterHome[player_index]
    if player.battingAverage > random.random():
        # ...
    else:
        # ...
if Game.outs == 3:
    # Reached 3 outs
else:
    # No players left and game outs < 3

The error happens because rosterHome is a list of instances of the Player class, so when you iterate on the list (for i in rosterHome) each element will be an instance of said class (i is a Player). If you want to access the number of each player you'll have to access the attribute number of your Player 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:

while Game.outs < 3:
    for player in rosterHome:
        # x wanted to access a player, but we don't need to do that actually
        if player.battingAverage > random.random():
            # ...
        else:
            # ...

This part of the answer considers that you actually want to meet both requirements (number of outs and iterate players once):

player_index = 0
while Game.outs < 3 and player_index< len(rosterHome):
    player = rosterHome[player_index]
    if player.battingAverage > random.random():
        # ...
    else:
        # ...
if Game.outs == 3:
    # Reached 3 outs
else:
    # No players left and game outs < 3
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文