我有一堂课,我为每个实例分配一个评分。
class Team:
def __init__(self, rating):
"Initialize team with rating"
self.rating = rating
我希望能够遍历评分列表,并为每个评分创建一个实例,因此,如果我有评分和团队名称的列表,则如下所示:
scores = [10, 11, 12, 13]
teams = ['tm0', 'tm1', 'tm2', 'tm3']
for t, s in zip(teams, scores):
t = Team(s)
tm2.rating # returns 12
上面没有定义我想要的Team实例。
我是Python的新手,所以怀疑有一个简单的修复程序,或者是更Python化的方法。
答案 0 :(得分:3)
您似乎想要一个dict
来将每个团队的名称映射到Team
的实例。
scores = [10, 11, 12, 13]
team_names = ['tm0', 'tm1', 'tm2', 'tm3']
teams = {t: Team(s) for t, s in zip(team_names, scores)}
assert teams['tm0'].rating == 10
答案 1 :(得分:0)
您可以使用exec在这里实现您想要的东西:
for t,s in zip(teams, scores):
exec(f"{t} = Team({s})")