0

I have a class where I assign a rating to each instance.

class Team:

def __init__(self, rating):
    "Initialize team with rating"
    self.rating = rating

I would like to be able to loop over a list of ratings, and create an instance for each rating, so if I have a list of ratings and team names, something like this:

scores = [10, 11, 12, 13]
teams = ['tm0', 'tm1', 'tm2', 'tm3']

for t, s in zip(teams, scores):
    t = Team(s)

tm2.rating    # returns 12

The above is not defining an instance of Team like I want it to.

I am new to Python so suspect there is an easy fix, or a more Pythonic way of doing this.

  • Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – quamrana Jun 04 '19 at 16:50

2 Answers2

3

You appear to want a dict that maps each team name to an instance of 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
chepner
  • 497,756
  • 71
  • 530
  • 681
  • `z2` isn't really necessary, *unless* you need to save a reference to the object before assigning something else to the key with something like `teams['tm2'] = Team(15)`. – chepner Jun 04 '19 at 17:03
  • Sorry, I just deleted the comment you replied to as I thought your edit (which I missed) resolved my question. – galelamanzi Jun 04 '19 at 17:05
0

You can achieve what you want here with exec:

for t,s in zip(teams, scores):
    exec(f"{t} = Team({s})")
PirateNinjas
  • 1,908
  • 1
  • 16
  • 21
  • Can I ask why this is being downvoted? It works perfectly for me - is it because it is un-Pythonic in some way? – galelamanzi Jun 04 '19 at 16:59
  • 1
    Generally speaking I would avoid using exec, as it executes an arbitrary command, which could have unexpected consequences. – PirateNinjas Jun 04 '19 at 17:02