2017-05-03 7 views
0

hi.txtファイルからデータを読み込もうとしていますが、アップロードした画像にhi.txtの内容が表示されます。どうすればtxtファイルからデータを読み込み、Pythonのリストにするのですか?

私は何をしようとしていますが、データが正確に

X = [[0, 0], [0, 1], [1, 0], [1, 1]] 
Y = [[0], [1], [1], [0]] 

以下のように私は私のコードを持っていることは

X=[] 
Y=[] 

あると、hi.txtがcに位置して見えるようにすることです:ルックス

#XOR 
#X1 X2 Y 
0 0 0 
0 1 1 
1 0 1 
1 1 0 

そして、私はを読み取ることによって、そのようなデータ構造を作るために行うことになっていますようにtxtデータ..?

答えて

0

使用numpy.loadtxt

In [30]: arr = np.loadtxt('Desktop/a.txt') 

In [31]: X, Y = arr[:,:2], arr[:,2:] 

In [32]: X 
Out[32]: 
array([[ 0., 0.], 
     [ 0., 1.], 
     [ 1., 0.], 
     [ 1., 1.]]) 

In [33]: Y 
Out[33]: 
array([[ 0.], 
     [ 1.], 
     [ 1.], 
     [ 0.]]) 
0

これは私がそう思うはずです。

x=[] 
y=[] 
with open("myfile.txt", encoding="utf-8") as file: 
    arr_content = file.readlines() 
    for eachline in arr_content: 
     values = eachline.split() 
     x.append([values[0],values[1]]) 
     y.append(values[2]) 
0
with open("hi.txt") as f: 
    X ,Y = [], [] 
    for line in f: 
     if not line.startswith("#"): 
      x1, x2, y1 = line.strip().split() 
      X.append([x1, x2]) 
      Y.append([y1]) 
+0

あなたが自分自身に全体のリストを追加しています。 –

+0

typo mistake、今修正しました – Hackaholic

+0

今あなたは上書きしていますね。 –

0
X = [[None for x in range(2)] for y in range(4)] 
Y = [[None] for y in range(4)] 
i=0 
with open('hi.txt', 'r') as file: 
    for row in file: 
     if row[0]!="#": 
      a, b, c = row.split() 
      print ("\nReading row # %d from file: %s") %(i, row) 
      X[i]=[int(a),int(b)] 
      Y[i]=[int(c)] 
      i+=1 
      print "X[] is now:", X 
      print "Y[] is now:", Y 

print ("\n\nFinal Output:") 
print (X) 
print (Y)