Reading a triangle of numbers into a 2d array of ints in Python

Posted by Gabriel Silk on Stack Overflow See other posts from Stack Overflow or by Gabriel Silk
Published on 2010-04-26T07:21:41Z Indexed on 2010/04/26 7:23 UTC
Read the original article Hit count: 291

Filed under:

I want to read a triangle of integer values from a file into a 2D array of ints using Python. The numbers would look like this:

75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 ...

The code I have so far is as follows:

f = open('problem18.input', 'r')
arr = []
for i in range(0, 15):
    arr.append([])
    str = f.readline()
    a = str.split(' ')
    for tok in a:
        arr[i].append(int(tok[:2]))

print arr

I have a feeling this could be done in a tighter, more Pythonesque way. How would you do it?

© Stack Overflow or respective owner

Related posts about python