我無法重現您的錯誤。另外,在運行代碼時,我不會得到空數組。請參閱下面的代碼和結果。當輸入數據與您的一樣乾淨時,我仍然建議使用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