簡體   English   中英

將文本文件內容讀入整數列表

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

我有一個文件包含:

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'

希望對此有所幫助。

我們可以使用numpy.genfromtxt

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

使用列表推導和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]]

在您的代碼中,嘗試替換:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM