我想使用Python将一个整数值的三角形从文件读取为2D整数数组。这些数字如下所示:

75

95 64

17 47 82

18 35 87 10

20 04 82 47 65

...

到目前为止,我的代码如下:

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

我感觉这可以用更紧密,更Python化的方式来完成。你会怎么做?

最佳答案

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

关于python - 在Python中将数字三角形读入2d整数数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2711681/

10-16 20:18
查看更多