0

I have a text file that I want my program (in python 3.2) to read as (1) every line as a list and then (2) I want to make new list that contain elements with same index in (1). like this:

shagy 2 3 4 5 6  
dely 3 4 5 6 7 

horizental lists = [shagy,2,3,4,5,6] and [dely,3,4,5,6,7]  
vertical lists = [shagy,dely] and [2,3] and [3,4] and [4,5] and [5,6] and [6,7] 

I need to do this because I'm supposed to find the max value of each column (elements with the same index). So I thought if I put them in a list it would be easier to find their maximum,but I don't know how to write that.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

1

Use .split() to split lines into lists, and use zip(*lines) to turn the rows into columns.

with open('filename') as inputfile:
    rows = [line.split() for line in inputfile]

columns = zip(*rows)

The values in the rows are still string values, but you could now map them to int:

int_columns = [map(int, col) for col in columns[1:]]

This skips the first column, with the names.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • if i want to find the max of each column i can write max(int_columns) and this will give me a list that contains all the max values of of each column? –  Mar 29 '13 at 17:30
  • @shaghayeghtavakoli: You need to apply `max` to each column contained *in* `int_columns`. Loop with `for column in int_colums:` for example. – Martijn Pieters Mar 29 '13 at 17:31
  • yes your answer was very helpful.hope you can answer my other questions as well since stackoverflow is my only 'help source' for python. –  Mar 29 '13 at 18:36
  • now it's green:).Do i have to write another for loop if i want to divide all the members of the column with the max value? If yes, how would the for loop look like? Because all the column elements must be divided by columns max value and then multiplied by a number.(this number is chosen by the person who is using the program so it can change from 0 to 5 and for every column is different.I'm guessing another for loop here!!!) –  Mar 29 '13 at 18:48