将文本文件内容读入整数列表

时间:2018-08-28 03:42:27

标签: python

我有一个文件,其中包含:

1 3 3
1 5 6
2 4 9
2 4 8
4 5 7

,我想将其读入列表列表,其中:

[[1,3,3],[1,5,6],[2,4,9],[2,4,8],[4,5,7]]

我尝试过:

def main():
    filename = open("mytext.txt","r",encoding = "utf-8")
    file = filename
    lst = []

    for line in file:
        line = line.strip().split()
        lst.append(line)

    for val in range(len(lst)):
        val = int(lst[val])

    print(lst)

main()

但是我说错了

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

希望对此有所帮助。

3 个答案:

答案 0 :(得分:3)

我们可以使用numpy.genfromtxt

import numpy as np
answer = np.genfromtxt('Test.txt', dtype=np.int64).tolist()

答案 1 :(得分:1)

使用列表推导和readlines

In [107]: with open('mytext.txt', encoding='utf-8') as file_pointer:
     ...:     lst = [[int(j) for j in i.split()] for i in file_pointer.readlines()]

列表推导通常比其他方法快得多且可读性强。

上述方法类似于

In [111]: with open('mytext.txt', encoding='utf-8') as file_pointer:
     ...:     lst = []
     ...:     for i in file_pointer.readlines():
     ...:         inner_lst = []
     ...:         for j in i.split():
     ...:             inner_lst.append(int(j))
     ...:
     ...:         lst.append(inner_lst)
     ...:

In [112]: lst
Out[112]: [[1, 3, 3], [1, 5, 6], [2, 4, 9], [2, 4, 8], [4, 5, 7]]

答案 2 :(得分:1)

在您的代码中,尝试替换:

for val in range(len(lst)):
    val = int(lst[val])

具有:

result = []

for row in lst:
    row_list = []
    for i in row.split():
        val = int(i.strip())
        row_list.append(var)
    result.append(row_list)

或更简洁:

result = [[int(i.strip()) for i in row.split()] for row in lst]