Path: csiph.com!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!nntp.club.cc.cmu.edu!micro-heart-of-gold.mit.edu!bloom-beacon.mit.edu!bloom-beacon.mit.edu!panix!gordon From: John Gordon Newsgroups: comp.lang.python Subject: Re: The sum of numbers in a line from a file Date: Thu, 20 Feb 2014 16:46:38 +0000 (UTC) Organization: PANIX Public Access Internet and UNIX, NYC Lines: 50 Message-ID: References: <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> NNTP-Posting-Host: panix3.panix.com X-Trace: reader1.panix.com 1392914798 4289 166.84.1.3 (20 Feb 2014 16:46:38 GMT) X-Complaints-To: abuse@panix.com NNTP-Posting-Date: Thu, 20 Feb 2014 16:46:38 +0000 (UTC) User-Agent: nn/6.7.3 Xref: csiph.com comp.lang.python:66775 In <882091da-a499-477e-8f50-c5bdde7cdfec@googlegroups.com> kxjakkk writes: > Let's say I have a sample file like this: > Name 1 2 3 4 5 6 7 8 > ------------------------------------------------------------------------ > name1 099-66-7871 A-F Y 100 67 81 59 98 > name2 999-88-7766 A-F N 99 100 96 91 90 > name3 000-00-0110 AUD 5 100 28 19 76 > name4 398-72-3333 P/F Y 76 84 49 69 78 > name5 909-37-3689 A-F Y 97 94 100 61 79 > For name1, I want to add together columns 4, 5, 6, and get an average from that, then do the same for the last two columns. I want to do this for every name. > All I've got is > sum([int(s.strip()) for s in open('file').readlines()]) This should get you started. However, this code does not work for all your imput lines, as 'name3' is missing the third field. You'll have to to modify the code to do something smarter than simple space-delimited data. But as I said, it's a start. # open the file with open('file') as fp: # process each line for line in fp.readlines(): # split the line into a list of fields, delimited by spaces fields = line.split() # grab the name name = fields[0] # convert text values to integers and sum them sum1 = int(fields[4]) + int(fields[5]) + int(fields[6]) sum2 = int(fields[7]) + int(fields[8]) # compute the averages average1 = sum1 / 3.0 average2 = sum2 / 2.0 # display output print '%s %f %f' % (name, average1, average2) -- John Gordon Imagine what it must be like for a real medical doctor to gordon@panix.com watch 'House', or a real serial killer to watch 'Dexter'.