简体   繁体   English

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

[英]Reading a text file content into a list of integers

I have a file containing: 我有一个文件包含:

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

and I want to read it into a list of list where: 我想将其读入列表列表,其中:

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

I tried: 我试过了:

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()

but I'm getting an error saying 但我说错了

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

Would appreciate some help on this. 希望对此有所帮助。

We can use numpy.genfromtxt 我们可以使用numpy.genfromtxt

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

Use list comprehensions and readlines 使用列表推导和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()]

List comprehensions are often much faster and more readable than other methods. 列表理解通常比其他方法快得多并且可读性强。

The above method is similar to 上面的方法类似于

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

In your code, try replacing: 在您的代码中,尝试替换:

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

with: 与:

result = []

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

or more succintly: 或更简洁地:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM