我正在尝试使用 Python 从文件中读取一些数字并将它们存储到矩阵中。在文件中,在第一行,我有 2 个数字,n 和 m,行数和列数,在下一行,我有 n*m 值。复杂的部分是,在文件中,在第二行,例如,我没有 m 值,我只有 m-2 值。因此,我无法一次读取一行文件并将值存储在矩阵中。编辑文件不是选项,因为我的文件有 200 行和 1000 列。 这是行数和列数较少的文件的外观:
4 5
1 2 3
4 5 1 2 3 4
5 1 2
3 4 5 1 2
3 4 5
我已经成功解决了这个问题,方法是将所有值存储在一个数组中,然后删除前两个值(n 和 m),然后从该数组创建一个矩阵。
这是我的代码:
f = open('somefile2.txt')
numbers = []
for eachLine in f:
line = eachLine.strip()
for x in eachLine.split(' '):
line2 = int(x)
numbers.append(line2)
f.close()
print numbers
n = numbers[0]
del numbers[0]
m = numbers[0]
del numbers[0]
print n, m, numbers
vector = []
matrix = []
for i in range(n):
for j in range(m):
vector.append(numbers[j])
matrix.append(vector)
vector = []
print matrix
这给了我预期的结果,但是这是通过使用额外的数组numbers
来做到这一点的正确方法,还是有一种更简单的方法可以将所有值直接存储到矩阵?
最佳答案
您可以使用生成器函数:
def solve(f, n, m):
lis = []
for line in f:
if len(lis) > m:
yield lis[:m]
lis = lis[m:]
lis.extend(map(int, line.split()))
for i in xrange(0, len(lis), m):
yield lis[i:i+m]
with open('abc1') as f:
n, m = map(int, next(f).split())
# Now you can either load the whole array at once using the list() call,
# or use a simple iteration to get one row at a time.
matrix = list(solve(f, n, m))
print matrix
输出:
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
另一种方法是获取文件中所有项目的扁平化迭代器,然后将该迭代器拆分为大小相等的 block 。
from itertools import chain, islice
with open('abc1') as f:
n, m = map(int, next(f).split())
data = chain.from_iterable(map(int, line.split()) for line in f)
matrix = [list(islice(data, m)) for i in xrange(n)]
print matrix
#[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
相关:
关于python - 使用 python 读取文件并将值存储在矩阵中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21233784/