从文本文件读取矩阵到数组

时间:2016-01-19 04:07:48

标签: python-3.x

我有文件matrix.txt,它是:

0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

我试图逐行读取它,并将每一行拆分成一个数组。现在,我有以下代码段:

with open('matrix.txt', 'r') as f:
    for line in f:
        line = line.strip()
        if len(line) > 0:
            l.append(map(int, line.split()))
    print(l)

但这给了我输出:

[<map object at 0x105af8ba8>, <map object at 0x105af8c50>, <map object at 0x105af8cf8>, <map object at 0x105af8e10>, <map object at 0x105af8da0>, <map object at 0x105af8b70>, <map object at 0x105af8400>, <map object at 0x105af8a90>, <map object at 0x105b07128>, <map object at 0x105b071d0>, <map object at 0x105b07240>, <map object at 0x105b073c8>, <map object at 0x105af8c88>, <map object at 0x105b070f0>, <map object at 0x105b074a8>, <map object at 0x105b07518>, <map object at 0x105b075c0>, <map object at 0x105b076a0>]

当我真正想要的是整数数组时,我可以迭代数组并根据需要提取特定值,并在矩阵中打印相应的行和列索引。我搞砸了什么?

2 个答案:

答案 0 :(得分:0)

你快到了。我认为这是让你失望的地图。我假设你想要l成为整数列表(或整数数组的数组)的列表。您的代码是整数映射列表。用以下代码替换l.append行:

-a "some thing"

地图是比列表/数组更高级的数据结构,并不是用于此类矩阵的正确数据结构。

答案 1 :(得分:0)

您可以使用list comprehension代替地图。

int i = 0;
var selected = repository.Invoices.ToList().OrderBy(i => i.Date).Select(x => new IndexedInvoice(){Index = i++, Invoice = x});