将Python文件读入二维列表

5

我有一个像这样的txt文件:

1 3 4
5 5 6

我希望能够将其元素解析为元组或列表。目前,我已经能够逐行读取文件,但结果并不是我想要的。

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

然而,当我打印该数组时,我得到了:
['1 3 4', '5 5 6']

what I want is

[[1, 3, 4], [5, 5, 6]]

是否有任何方法可以实现这一点?


1
这与元组有什么关系? - Henry Keiter
1
“[1 3 4]”是什么意思?这不是有效的Python表达式。你是不是想说“[1,3,4]”? - Elisha
是的,你说得对!这就是我想要的。 - JmRag
9个回答

7
with open("input.txt", "r") as file:
    result = [[int(x) for x in line.split()] for line in file]

5
如果我正确理解您的问题,您正在寻找str对象的split方法。您可能还想使用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]]

以下代码行执行相同的操作,但更加简洁和符合Python风格:
data = [[int(n) for n in line.split()] for line in ins]

最后,如果你真的想使用元组而不是列表,只需要在内部列表上使用 tuple 类型即可:

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

1
一行代码时间:
[line.split() for line in ins]

如果您想将项目转换为int,请随意这样做:
[map(int, line.split()) for line in ins]

@tim 那又怎样?提问者并没有读取文件的问题。 - Henry Keiter
1
这并不能证明缺乏完整答案的合理性。添加另一行只需要10秒钟,可以避免混淆。 - tim

1
with open('input.txt') as f:
    data = [map(int, line.split()) for line in f]

这基本上等同于更冗长的写法:
try:
    f = open('input.txt', 'r')
    data = []
    for line in f:
        data.append([int(n) for n in line.split()])
finally:
    f.close()

1

这是有效的

列表示例:

with open('yourfile.txt', 'r') as ins:
    array = [[int(n) for n in line.split()] for line in ins]

示例输出:

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

或者对于元组:
 with open('yourfile.txt', 'r') as ins:
     myTuple = tuple(tuple(int(n) for n in line.split()) for line in ins)

例子输出:
((1, 2, 3), (4, 5, 6), (7, 8, 9))

使用with意味着文件仅为块中的语句打开,并随后自动关闭。这是一种良好的实践。

0

有很多方法...

def read_text(path):
    with open(path, 'r') as file:
        line_array = file.read().splitlines()
        cell_array = []
        for line in line_array:
            cell_array.append(line.split())
        return cell_array

一点压缩:
def read_text(path):
    with open(path, 'r') as file:
        line_array = file.read().splitlines()
        cell_array = [line.split() for line in line_array]
        return cell_array

更高效的压缩!

def read_text(path):
    return [[item for item in line.split()] for line in open(path)]

0
你可以使用嵌套的列表推导式:
txt='''\
1 3 4
5 5 6'''

print [[int(s) for s in line.split()] for line in txt.splitlines()]
# [[1, 3, 4], [5, 5, 6]]

0
如果您真的希望输出与您所展示的完全相同,没有单引号和数字之间没有逗号,您只需将最后一行 print array 更改为以下内容即可:
print str(["[%s]"%item for item in array]).replace("'","")

-2
n = int(input())
l = []
for i in range(n):
    l.append(list(map(int, input().rstrip().split(" "))))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接