On Thursday, 20 February 2014 16:22:00 UTC, kxjakkk wrote: > 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.
The following solution works for Python3 (due to the unpacking using the * syntax) ---- from collections import defaultdict, namedtuple info = namedtuple('info', 'sum avg') interesting_data = (x.strip(' \n') for idx, x in enumerate(open('file').readlines()) if idx > 1 and len(x.strip(' \n')) > 0) split_points = [2, 4, 5] results = defaultdict(list) for line in interesting_data: name, _, _, _, *rest = line.split() last_point = 0 for point in split_points: s = sum(map(int, rest[last_point:point])) i = info(s, s / (point - last_point)) results[name].append(i) last_point = point print(results) print(results['name3'][0].avg) --Simon Kennedy -- https://mail.python.org/mailman/listinfo/python-list