转换多行字符串并将每一行读取为整数

时间:2018-09-05 07:48:57

标签: python

line.read包含

25,26,27,28,29,30,31,32.33,34,35,36,37,38,39,40.25,26,27,28,29,30,31,32.33,34,35,36,37,38,39,40.25,26,27,28,29,30,31,32.33,34,35,36,37,38,39,40.25,26,27,28,29,30,31,32.33,34,35,36,37,38,39,40

我的单行阅读器在这里

output = open('line.read', 'r')  # See the r
nodes_list = output.read().strip().split('.')
mylist = [[int(cell) for cell in row.split(',')] for row in nodes_list]

我的输出就是这段代码。

['25,26,27,28,29,30,31,32', '33,34,35,36,37,38,39,40', '25,26,27,28,29,30,31,32', '33,34,35,36,37,38,39,40', '25,26,27,28,29,30,31,32', '33,34,35,36,37,38,39,40', '25,26,27,28,29,30,31,32', '33,34,35,36,37,38,39,40']

此代码仅读取一行,但是我想读取多行并将其转换为8x8整数数组。旧值对我来说并不重要。我只想阅读当前行。我怎样才能做到这一点 ?它将读取第一行,之后将显示第二行等。

我的txt是这样的

25,26,27,28,29,30,31,32.33,34,35,36,37,38,39,40.25,26,27,28,29,30,31,32.33,34,35,36,37,38,39,40.25,26,27,28,29,30,31,32.33,34,35,36,37,38,39,40.25,26,27,28,29,30,31,32.33,34,35,36,37,38,39,40
22,33,21,33,40,37,24,23.15,13,12,35,33,12,15,23.22,33,21,33,40,37,24,23.15,13,12,35,33,12,15,23.22,33,21,33,40,37,24,23.15,13,12,35,33,12,15,23.22,33,21,33,40,37,24,23.15,13,12,35,33,12,15,23
...

我可以通过查找空单元格来找到它,也可以在我的txt文件中添加一个特殊字符,该文件可以知道行尾。但是,如果我这样做,它将以字符串形式读取它并显示所有值。它应该逐行执行该操作。感谢您的帮助

1 个答案:

答案 0 :(得分:1)

尽管对我来说还不是很清楚,但是我认为这就是你想要的。

with open('test.txt','r') as fout:
    line = fout.readline()
    while line:
        a = [[int(col) for col in row.split(',')] for row in line.split('.')]
        print(a)
        #Do something with your list a
        line = fout.readline()

print()函数的输出:

[[25, 26, 27, 28, 29, 30, 31, 32], [33, 34, 35, 36, 37, 38, 39, 40], [25, 26, 27, 28, 29, 30, 31, 32], [33, 34, 35, 36, 37, 38, 39, 40], [25, 26, 27, 28, 29, 30, 31, 32], [33, 34, 35, 36, 37, 38, 39, 40], [25, 26, 27, 28, 29, 30, 31, 32], [33, 34, 35, 36, 37, 38, 39, 40]]
[[22, 33, 21, 33, 40, 37, 24, 23], [15, 13, 12, 35, 33, 12, 15, 23], [22, 33, 21, 33, 40, 37, 24, 23], [15, 13, 12, 35, 33, 12, 15, 23], [22, 33, 21, 33, 40, 37, 24, 23], [15, 13, 12, 35, 33, 12, 15, 23], [22, 33, 21, 33, 40, 37, 24, 23], [15, 13, 12, 35, 33, 12, 15, 23]]

最后但并非最不重要的一点是,核心Python库中没有数组。当您指的是数组时,请始终说“列表”。