我无法重现您的错误。另外,在运行代码时,我不会得到空数组。请参阅下面的代码和结果。当输入数据与您的一样干净时,我仍然建议使用np.genfromtxt
。
代码:
import numpy as np
# I have input.txt in same directory as this .py-file
# np.genfromtxt with int and with string
approach1a = np.genfromtxt('input.txt', dtype=int)
approach1b = np.genfromtxt('input.txt', dtype=np.str_)
# list comprehension
approach2 = []
with open('input.txt') as file:
approach2 = [str(line) for line in file]
# like your approach, but without a, b and the if statement
approach3 = []
with open('input.txt') as file:
for line in file:
approach3.append(line)
# your code
inn = open("input.txt", "r")
a = 0
b = 10
array = []
while not a == b:
for i, line in enumerate(inn):
if i == a:
array += str(line)
a+=1
结果:
>>> approach1a
array([ 7, 4, 2, 5, 2, 9, 8, 6, 10, 8, 4])
>>> approach1b
array(['7', '4', '2', '5', '2', '9', '8', '6', '10', '8', '4'],
dtype='<U2')
>>> approach2
['7\n', '4\n', '2\n', '5\n', '2\n', '9\n', '8\n', '6\n', '10\n', '8\n', '4']
>>> approach3
['7\n', '4\n', '2\n', '5\n', '2\n', '9\n', '8\n', '6\n', '10\n', '8\n', '4']
>>> array
['7', '\n']
只有inpur文件的第一行是读你的代码的原因是因为与open
您可以通过线只迭代一次。如果你这样做了,你不能回去。要了解这一点,请参阅@Aaron Hall的例子this question:只有一个方法next
,但无法返回(在这种情况下返回一行)。当您将a
的值设置为1
时,即您将输入文件的第一行添加到array
后,您已达到所有行open
都被使用一次。这就是为什么我明白你的代码只读第一行,为什么我不能复制你声称你有array
作为一个空列表,为什么我建议approach3
。
你根本没有修改'array' ... –
如何在你的'if'块中放置一个print来查看它是否被实际执行? – khelwood
只需使用'array = numpy.genfromtxt(filename,dtype = int)'将这些值读入变量'array'。 – Michael