2017-07-07 69 views
0

有一个输入文件“input.txt”。它看起来像:为什么这段代码执行错误?

7 
4 
2 
5 
2 
9 
8 
6 
10 
8 
4 

而且还有一个代号:

inn = open("/storage/emulated/0/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 
print(array) 

我需要把所有的数字中的“数组”变量,但wher我运行的代码 - 我得到空“数组” 。代码中有错误吗?

(对于这样的noob问题抱歉)

+0

你根本没有修改'array' ... –

+0

如何在你的'if'块中放置一个print来查看它是否被实际执行? – khelwood

+0

只需使用'array = numpy.genfromtxt(filename,dtype = int)'将这些值读入变量'array'。 – Michael

回答

1

我无法重现您的错误。另外,在运行代码时,我不会得到空数组。请参阅下面的代码和结果。当输入数据与您的一样干净时,我仍然建议使用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

+0

非常感谢:) – maxpushka