4

I am new to learning Python, here is my current code:

#!/usr/bin/python

l = []
with open('datad.dat', 'r') as f:
  for line in f:
    line = line.strip()
    if len(line) > 0:
      l.append(map(float, line.split()))
print l[:,1]

I attempted to do this but made the mistake of using FORTRAN syntax, and received the following error:

  File "r1.py", line 9, in <module>
print l[:,1]

TypeError: list indices must be integers, not tuple

How would I go about getting the first row or column of an array?

Aaron Critchley
  • 2,335
  • 2
  • 19
  • 32
Richard Rublev
  • 7,718
  • 16
  • 77
  • 121

1 Answers1

6

To print the first row use l[0], to get columns you will need to transpose with zip print(list(zip(*l))[0]).

In [14]: l = [[1,2,3],[4,5,6],[7,8,9]]  
In [15]: l[0] # first row
Out[15]: [1, 2, 3]    
In [16]: l[1] # second row
Out[16]: [4, 5, 6]   
In [17]: l[2] # third row
Out[17]: [7, 8, 9]    
In [18]: t =  list(zip(*l)) 
In [19]  t[0] # first column
Out[19]: (1, 4, 7)    
In [20]: t[1] # second column
Out20]: (2, 5, 8)   
In [21]: t[2] # third column
Out[21]: (3, 6, 9)

The csv module may also be useful:

import csv

with open('datad.dat', 'r') as f:
   reader = csv.reader(f)
   l = [map(float, row) for row  in reader]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • 1
    Performing a full transpose every time you want to select a column would be wasteful, though. If you only need one column, a list comprehension like `[row[0] for row in l]` would be better; if you need to select columns repeatedly, it would be a good idea to store the transposed form. – user2357112 Apr 22 '15 at 09:48
  • @user2357112, it is just an example, I was not actually recommending transposing every time you want a column ,edited. – Padraic Cunningham Apr 22 '15 at 09:52