2017-07-07 77 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