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?

2
  • I think this answer will be quite helpful. Commented Apr 22, 2015 at 9:37
  • If you need to do a lot of numeric computation, look into numpy. It's an extremely powerful tool. Commented Apr 22, 2015 at 9:50

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

2 Comments

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, it is just an example, I was not actually recommending transposing every time you want a column ,edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.