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
,pos
get hold of elements inself.names
,self.salaries
,self.positions
which 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_row
string local variable - we write
nba_row
to 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,
nme
andpos
using the elements fromself.names
, andself.positions
, respectively - uses an
if
statement to check ifpos
is a key insort_by_pos
- if it is, it will add
nme
to the list set as the value attached topos
- if it isn't, it will add
pos
as a key insort_by_pos
, and then a list containingnme
as 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_nme
with the value ofself.names_by_pos()
- Initializes a dictionary
num_of_pos
- uses a
for in
loop to go through each key inpos_and_nme
, withpos
as the iterator- adds the key
pos
and sets the value to the length of the list attached topos
inpos_and_nme
tonum_of_pos
- adds the key
- Returns
num_of_pos