Python将文件读入2d列表

时间:2014-01-20 15:47:22

标签: python

我有一个这样的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']

我想要的是

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

有什么办法可以实现吗?

9 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:5)

如果我理解您的正确要求,那么您正在寻找str intdata = [] 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]] 对象的方法。您可能还想使用data = [[int(n) for n in line.split()] for line in ins] 类型来获取实际数字,而不是字符串:

tuple

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

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

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

{{1}}

答案 2 :(得分:1)

单行时间:

[line.split() for line in ins]

如果您想将项目转换为int,请随时执行此操作:

[map(int, line.split()) for line in ins]

答案 3 :(得分: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]]

答案 4 :(得分:0)

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

答案 5 :(得分:0)

这是有效的

列表:

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表示只为语句打开文件 在块内,然后自动关闭。这是一个很好的做法。

答案 6 :(得分:0)

如果您确实想要显示输出,但没有单引号且数字之间没有逗号,您只需将最后一行print array更改为:

print str(["[%s]"%item for item in array]).replace("'","")

答案 7 :(得分: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)]

答案 8 :(得分:-1)

arr = ['a', 'b', 'c', 'd', 'e']
i = 0
puts arr.group_by { |x| i += 1; i % 1 }
i = 0
puts arr.group_by { |x| i += 1; i % 2 }
i = 0
puts arr.group_by { |x| i += 1; i % 3 }