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.
Advertisement
Answer
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