Python 2D array

Getting the averages of the columns

Page 1 of 1

1 Replies - 3097 Views - Last Post: 07 December 2009 - 12:14 AM Rate Topic: ***** 1 Votes

#1 Blizz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 19-August 09

Python 2D array

Post icon  Posted 05 December 2009 - 09:42 PM

Hey, this code is to output an array of numbers from a text file, and also the totals and averages of each of the columns. I have it so far that it outputs the array along with the totals and averages of the rows, and the totals for the columns. I am having trouble outputting the averages for the columns however. Can someone please point me in the right direction?

Just some additional explanation, if the text file reads:
12, 31, 12
5, 3, 12
32, 12, 2
My program currently will output:
[12, 31, 12, 55, 18.33]
[5, 3, 12, 20, 6.67]
[32, 12, 2, 46, 15.33]
[49, 46, 26]

I need another row underneath all of that contains the averages of each column.

# Python 3.1

import sys

def split(l):
	r = []
	n = l.count(',')
	for i in range(n):
		r = r + [int(l[0:l.index(',')])] #convert text to an integer
		l = l[l.index(',') +1:len(l)] # remove text
		# on next iteration, next value will be considered
	r = r + [int(l)] # last element
	return r



f = sys.stdin
fn = "C:\\Users\Elisha\Documents\CS1MA3\Python\E3.txt" 
f = open(fn,'r')
l = f.readline()
if l[len(l)-1] == '\n':
	l = l[0:len(l)-1]
x = []
while l != '':
	x = x + [l]
	l = f.readline()
	if l != '' and l[len(l)-1] == '\n':
		l = l[0:len(l) - 1]
f.close()


t = []

for i in x:
	new = split(i)
	t.append(new)
	total = sum(split(i))
	average = round(total/len(new), 2)
	print(split(i) + [total] + [average])

result = [0] * len(t)

for c in range(len(t[0])):
	for r in range(len(t)):
		result[c] += t[r][c]
print(result)


Thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: Python 2D array

#2 bodom658  Icon User is offline

  • Villiage Idiom
  • member icon

Reputation: 112
  • View blog
  • Posts: 1,123
  • Joined: 22-February 08

Re: Python 2D array

Posted 07 December 2009 - 12:14 AM

embedded for loop, a few variables, and some division.

This is my hint.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1