使用NumPy从文件读取非统一数据到数组

loo*_*arc 13 python file-io numpy

假设我有一个如下所示的文本文件:

33 3
46 12
23 10 23 11 23 12 23 13 23 14 23 15 23 16 24 10 24 11 24 12 24 13 24 14 24 15 24 16 25 14 25 15 25 16 26 16 27 16 28 16 29 16
33 17 33 18 33 19 34 17 34 18 34 19 35 17 35 18 35 19 36 19
41 32 41 33 42 32 42 33

我想将每一行读入一个单独的整数数组,如(伪代码):

for line in textfile:  
    currentArray = firstLine  
    do stuff with currentArray
Run Code Online (Sandbox Code Playgroud)

在第一次迭代中,currentArray将是

数组([33,3])

在第二次迭代中,currentArray将是

数组([46,12])

直到最后一次迭代,当currentArray将是

阵列([41,32,41,33,42,32,42,33])

基本上,我想拥有numpy函数loadtxt的功能:

currentArray = loadtxt('scienceVertices.txt',usecols =())

除了usecols,能够指定行,例如,

currentArray = loadtxt('scienceVertices.txt',userows =(line))

Pau*_*aul 14

这是一个单行:

arrays = [np.array(map(int, line.split())) for line in open('scienceVertices.txt')]
Run Code Online (Sandbox Code Playgroud)

arrays 是一个numpy数组的列表.


pay*_*yne 6

for line in textfile:
  a = np.array([int(v) for v in line.strip().split(" ")])
  # Work on your array
Run Code Online (Sandbox Code Playgroud)