1

Very new python programmer here.

I'm trying to take a list of people's names and information (in this case, baseball players) and create a different object for each player with attributes based on the other information in those strings. So for example, I have the following list of people stored in a list called my_players (of course, my actual list of players is much longer):

SS Derek_Jeter Yankees
P Johan_Santana Mets
C Ivan_Rodriguez Tigers

I'd like to create objects of the class Player, where Player is defined as:

class Player():
    def __init__(self,full_name,pos,team_name):
        self.name = full_name
        self.position = pos
        self.team = team_name

But I don't want to have to manually create each object, I want to use a for loop that, for each string in my_players, uses the second word in the string to be the name of the object, then the three parts of the string to be the attributes. That is, I'll want one object called Derek_Jeter with the attributes Derek_Jeter, SS, Yankees, and another object called Johan_Santana, and another called Ivan_Rodriguez, but I don't want to type each of those object names into my code. How can I create objects this way?

jamieg
  • 13
  • 2
  • 1
    http://stackoverflow.com/questions/15081542/python-creating-objects check out how to create objects in this link. Loop through the object creation using string.split(). – FirebladeDan Aug 09 '15 at 00:32

3 Answers3

3

Here you go:

content = """SS Derek_Jeter Yankees
P Johan_Santana Mets
C Ivan_Rodriguez Tigers"""

lines = content.split("\n")

players = []
for x in lines:
  pos, name, team = x.split(' ')
  players.append( Player(name, pos, team) )

# players is a list of the Player objects
ErikR
  • 51,541
  • 9
  • 73
  • 124
  • NOOO! jaimeg is learning don't give em the answer out the gate come on. – FirebladeDan Aug 09 '15 at 00:33
  • @user5402 But won't this mean that the object for Jeter would be called players[0]? How can I make an object called Jeter from the list? Obviously I could write Jeter = players[0] but I'm trying to avoid having to name each player. – jamieg Aug 09 '15 at 01:18
  • You would write a function `findPlayer(name, playerlist)` which would return the player object in `playerlist` with the specified name. – ErikR Aug 09 '15 at 01:26
3
players = [('SS', 'Derek_Jeter', 'Yankees'), 
           ('P', 'Johan_Santana', 'Mets'), 
           ('C', 'Ivan_Rodriguez', 'Tigers')]
player_objs = [Player(name, position, team) for position, name, team in players]

Edit: Sorry, I misread and thought the player position, name, and team was already in a list.

Given your string 'list' of players:

player_strings = """SS Derek_Jeter Yankees
                 P Johan_Santana Mets
                 C Ivan_Rodriguez Tigers"""

You can turn this into a proper list with:

players = [line.split(' ') for line in content.split('\n')]

This is roughly equivalent to this portion of @User5402's code:

lines = content.split("\n")
players = []
for x in lines:
    pos, name, team = x.split(' ')

It's a useful feature in Python called the list comprehension: https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

If you want to condense @User5402's code into one line it would be:

player_objs = [Player(name, position, team) for position, name, team in [line.split(' ') for line in content.split('\n')]]

If you want to be able to call players by name you can create a dictionary with your Player() objects as values using a dictionary comprehension (see: Create a dictionary with list comprehension in Python for more examples):

player_objs_dict = {name:Player(name, position, team) for position, name, team in [line.split(' ') for line in content.split('\n')]}

You can then get player objects by:

#will return the Derek Jeter object
player_objs_dict['Derek_Jeter']
Community
  • 1
  • 1
NJM
  • 565
  • 3
  • 13
  • Could you please [edit] in an explanation of why this code answers the question? Code-only answers are [discouraged](http://meta.stackexchange.com/q/148272/274165), because they don't teach the solution. (This also doesn't appear to do much about naming variables, or even array indexes or dictionary keys or anything, based on player names.) – Nathan Tuggy Aug 09 '15 at 01:12
  • I like the suggestion about using a dictionary. You could also consider using a `defaultdict(list)` to handle the case where multiple players have the same name. Each value of the dictionary would then be a list of `Player`s corresponding to the name serving as the key. – mattsilver Aug 10 '15 at 06:11
0

[Player(x,y,z) for y,x,z in map(lambda s: tuple(s.split()),my_players)]

should create the list of objects (if you want a 1-liner)

John Coleman
  • 51,337
  • 7
  • 54
  • 119