def record_per_row(self):
"""
Writes a CSV file with as many records as the size of any of the lists
A record is a row in the file, with three columns, corresponding to
a name, salary, and position.
"""
- Create 3-field records from the three attributes such that
- a record has elements at the same position in the three lists.
- Format a record as a string with the three elements separated by comma
- Write each record to the nba.txt text file
We use the accumulation pattern with accumulator nba_file
- Iteration is over three sequences simultaneously, the class attributes
- three loop variables
nme,slr,posget hold of elements inself.names,self.salaries,self.positionswhich have the same positions - we use
zip()built-in function to allow for parallel processing - we assemble string representations of the elements including the commas
and store in
nba_rowstring local variable - we write
nba_rowto the file object accumulatornba_file
- three loop variables
###names_by_pos()
def names_by_pos(self):
"""
Returns a dictionary with the keys are set to the names of the positions
and the values are set to lists of each name that is that position
"""
- Initializes a dictionary
sort_by_pos, which will be returned at the end of the method - Uses an accumulation pattern with the accumulator
sort_by_pos - Iterates over two loop variables,
nmeandposusing the elements fromself.names, andself.positions, respectively - uses an
ifstatement to check ifposis a key insort_by_pos- if it is, it will add
nmeto the list set as the value attached topos - if it isn't, it will add
posas a key insort_by_pos, and then a list containingnmeas the attached values
- if it is, it will add
- afterwards, the method will return
sort_by_pos
###most_played_position()
def most_played_position(self):
"""
Calls names_by_pos(), and uses the returned dictionary to find the
number of players in each position, before returning a dictionary with
the key being the position and the value being the number of players
with that position
"""
- Initializes a dictionary
pos_and_nmewith the value ofself.names_by_pos() - Initializes a dictionary
num_of_pos - uses a
for inloop to go through each key inpos_and_nme, withposas the iterator- adds the key
posand sets the value to the length of the list attached toposinpos_and_nmetonum_of_pos
- adds the key
- Returns
num_of_pos