Home  >  Q&A  >  body text

python可以用类的实例作为List元素么?

我把nba各个队的一些数据爬下来,用team类暂时保存。

class Team:
    team_name=""
    team_years=0
    def __init__(self,name,team_years):
        self.team_name=name
        self.team_years=team_years
        self.wlp=[]
    def addWLP(self,x):
        self.wlp.append(x)

然后希望将各个队保存在一个列表里。

def saveWLP():
    teams=getTeams()
    team_list=[len(teams)]
    i=0
    for team in teams:
        wlp=teamGetWLP(team)
        team_list[i]=Team(team,len(wlp))
        for j in range(len(wlp)):
            team_list[i].addWLP(wlp[j])
        i+=i
    return team_list

但是存完之后再调用只有 team_list[0]里存有最后一个被保存的队,而team_list[1]就是index out of range。
请问该如何解决?谢谢

阿神阿神2712 days ago326

reply all(2)I'll reply

  • PHPz

    PHPz2017-04-17 15:34:48

    Of course you can, nest any data structure

    reply
    0
  • 黄舟

    黄舟2017-04-17 15:34:48

    i+=i
    

    If you do thisiwon’t it always be 0? Your for team in teams loop is just setting team_list[0]

    reply
    0
  • Cancelreply