简体   繁体   中英

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

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

Use list comprehensions and 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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