由txt文件中的空格分隔的数字到python列表中

时间:2016-10-19 22:01:06

标签: python

我正在尝试将包含以空格分隔的数字行的txt文件转换为列表中逗号分隔的数字,其中每一行都是使用Python 3的这些数字的新列表。

E.g。 txt文件包含

  

1 2 3 4 5

     

6 7 8 9 10

我想在python中使用它:

[1,2,3,4,5]

[6,7,8,9,10]

我似乎无法找到一个好的解决方案,我使用了numpy并获得了列表而不是逗号分隔,例如: [[1 2 3 4 5],[6 7 8 9 10]]

以下是我使用过的示例代码并不是很有效:

import numpy as np

mymatrix = np.loadtxt('file')

感谢任何输入! (ps我是初学者,但想在我正在开发的程序中使用这些列表)

2 个答案:

答案 0 :(得分:0)

以下使用普通的Python 3(没有NumPy)

# open file
with open('file.txt') as fp:
    # 1. iterate over file line-by-line
    # 2. strip line of newline symbols
    # 3. split line by spaces into list (of number strings)
    # 4. convert number substrings to int values
    # 5. convert map object to list
    data = [list(map(int, line.strip().split(' '))) for line in fp]

这提供了您正在寻找的结果:

>>> with open('data.txt') as fp:
...     data = [list(map(int, line.strip().split(' '))) for line in fp]
... 
>>> print(data)
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

答案 1 :(得分:0)

我很确定你的numpy代码工作得很好,你只是不习惯它为显示格式化数组。

也许这会给你的结果更像你期待的结果:

import numpy as np

mymatrix = np.loadtxt('file')
print (np.array_repr(mymatrix))
相关问题