Newbee needs Help ref Using Function Statements not Loops(For)

Sean Ross frobozz_electric at hotmail.com
Wed Dec 3 19:27:28 CET 2003


"jstreet10" <jstreet10 at cox.net> wrote in message
news:DLozb.41415$Ac3.27964 at lakeread01...
> How would i use function statements instead of loops(for) in this code? i
> have tried some, but not working.
[snip]

I'm sure someone else will ask you why you want to do it this way,
since your code was already very clean and understandable, so I won't
bother - I'll just show you one way that it can be done without for loops,
and without list comprehensions (which use "for"). Someone else will
probably show you the list comprehension version.

# requires python 2.3+
import string
input_file = open("grades.txt","r")
records = input_file.readlines()
input_file.close()
commasplit = lambda record: string.split(record,",")
record_items = map(commasplit, records)
student_table = dict(record_items)
grade_counter = len(records)
# sum is a builtin in python 2.3
total = sum(map(int, student_table.values()))
average = total/grade_counter

student_names = student_table.keys()
student_names.sort()
output_file = open("processed.txt", "w")
rebuild_info = lambda student_name: \
                      student_name +"," + student_table[student_name]
student_info = map(rebuild_info, student_names)
map(output_file.write, student_info)
output_file.write("Average grade is " + str(average))
output_file.close()


Perhaps I misunderstood what you were asking for with
"function statements". Perhaps you wanted to define some
functions of your own? Or maybe you were looking for
some builtin functions that did this sort of processing?
I'm not sure.

Anyway, HTH,
Sean

p.s. Small note on your original code:

> for record in input_file.readlines():

in later versions of python this can be written as

    for record in input_file:







More information about the Python-list mailing list