开发者

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

开发者 https://www.devze.com 2022-12-27 23:19 出处:网络
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:

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('input.txt', '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?


arr = [[int(i) for i in line.split()] for line in open('input.txt')]


The ways I can think of would be...

    with open(path, 'r') as file:
        line_array = file.read().splitlines()
        cell_array = []
        for line in line_array:
            cell_array.append(line.split())
        print(cell_array)

A little compression :

    with open(path, 'r') as file:
        line_array = file.read().splitlines()
        cell_array = [line.split() for line in line_array]
        print(cell_array)

Even more compression !

    print([[item for item in line.split()] for line in open(path)])
0

精彩评论

暂无评论...
验证码 换一张
取 消