【问题标题】:reading a file and storing values in a matrix using python使用python读取文件并将值存储在矩阵中
【发布时间】:2014-01-20 12:12:22
【问题描述】:

我正在尝试从文件中读取一些数字并使用 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,还是有一种更简单的方法可以将所有值直接存储到矩阵中?

【问题讨论】:

    标签: python file list matrix


    【解决方案1】:

    您可以使用生成器函数:

    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]]
    

    另一种方法是获取文件中所有项目的扁平迭代器,然后将该迭代器拆分为大小相等的块。

    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]]
    

    相关:

    【讨论】:

    • 谢谢!它适用于第一个版本。我也会尝试第二种方法。我还有一个问题:在通知中我看到我收到了我的问题的 2 个答案,但我只能看到你的答案。你知道为什么吗?
    • @user1956190 其他答案已被删除,只有拥有 10K+ rep 的用户才能看到已删除的帖子。
    • @user1956190 很高兴有帮助。 ;-)
    【解决方案2】:

    我的 2 美分:

    with open('somefile.txt') as f:
        strings = f.read().split()
    
    numbers = map(int, strings)
    m = numbers.pop(0)
    n = numbers.pop(0)
    
    matrix = [numbers[i:i+n] for i in xrange(0, m*n, n)]
    

    在 Python 3 中,您只需这样做:

    m, n, *numbers = map(int, strings)
    

    根据你想对数据做什么,你可能想看看 NumPy,它有一些读取文本文件的好方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-01
      相关资源
      最近更新 更多