我有一个看起来像这样的文件:
1 2 3 4 5 6 7
1 0 1 1 1 1 1 1
2 0 0 1 1 1 1 1
3 0 0 0 1 1 1 1
4 0 0 0 0 1 1 1
5 0 0 0 0 0 1 1
6 0 0 0 0 0 0 1
7 0 0 0 0 0 0 0
我只想读入 1 和 0 并忽略顶部标题行和行名(第一列)。
到目前为止,我已设置好标题行,但如何才能跳过跳过列。到目前为止我的代码
with open('file') as f:
next(f) #skips header row
content = [x.strip('\n') for x in f.readlines()]
我试图只使用基本 python 而没有库。
最佳答案
使用简单的索引:
with open('file') as f:
next(f)
content = [x.strip().split()[1:] for x in f]
这将为您提供拆分的零和一个作为嵌套列表。
如果您不想拆分行,您仍然可以使用索引来删除第一个字符。
content = [x[1:].strip() for x in f]
或者作为 Numpythonic 方法,您可以使用 Numpy 的 loadtxt()
函数:
>>> import numpy as np
>>> from io import StringIO
>>> np.loadtxt(StringIO(my_string), skiprows=1)[:,1:]
array([[ 0., 1., 1., 1., 1., 1., 1.],
[ 0., 0., 1., 1., 1., 1., 1.],
[ 0., 0., 0., 1., 1., 1., 1.],
[ 0., 0., 0., 0., 1., 1., 1.],
[ 0., 0., 0., 0., 0., 1., 1.],
[ 0., 0., 0., 0., 0., 0., 1.],
[ 0., 0., 0., 0., 0., 0., 0.]])
关于python - 读取 txt 矩阵时,如何跳过第一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37393760/