在Python中将数字三角形读取到二维整数数组中

5 投票
2 回答
1634 浏览
提问于 2025-04-15 22:01

我想用Python从一个文件里读取一个整数三角形的数据,并把它存到一个二维整数数组里。这个数字的排列大概是这样的:

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风格的方法来实现。你会怎么做呢?

2 个回答

0

我能想到的几种方法是...

    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)

稍微压缩一下:

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

更强的压缩!

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

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。

撰写回答