Python将文件读入2d列表

JmR*_*Rag 3 python

我有一个这样的txt文件:

1 3 4
5 5 6
Run Code Online (Sandbox Code Playgroud)

我想将元素解析为元组或列表.到目前为止,我能够逐行读取文件,但结果不是我想要的

    ins = open( "input.txt", "r" )
    array = []
    for line in ins:
        line = line.rstrip('\n')
        array.append( line )
    ins.close()
    print array
Run Code Online (Sandbox Code Playgroud)

然而打印我得到的数组

['1 3 4', '5 5 6']
Run Code Online (Sandbox Code Playgroud)

我想要的是什么

[[1, 3, 4], [5, 5, 6]]
Run Code Online (Sandbox Code Playgroud)

有什么办法可以实现吗?

Bar*_*ski 5

with open("input.txt", "r") as file:
    result = [[int(x) for x in line.split()] for line in file]
Run Code Online (Sandbox Code Playgroud)


Hen*_*ter 5

如果我理解你正确的问题,你就是在寻找对象的split方法str.您可能还想使用该int类型来获取实际数字,而不是字符串:

data = []
for line in ins:
    number_strings = line.split() # Split the line on runs of whitespace
    numbers = [int(n) for n in number_strings] # Convert to integers
    data.append(numbers) # Add the "row" to your list.
print(data) # [[1, 3, 4], [5, 5, 6]]
Run Code Online (Sandbox Code Playgroud)

以下行做同样的事情,但是更紧凑和Pythonic方式:

data = [[int(n) for n in line.split()] for line in ins]
Run Code Online (Sandbox Code Playgroud)

最后,如果你真的想使用元组而不是列表,那么只需tuple在内部列表中使用类型:

data = [tuple(int(n) for n in line.split()) for line in ins]
print(data) # [(1, 3, 4), (5, 5, 6)]
Run Code Online (Sandbox Code Playgroud)