簡體   English   中英

如何從txt文件讀取數據並將其作為python中的列表

[英]how do I read data from txt file and make it as lists in python

我正在嘗試從hi.txt文件讀取數據,並且hi.txt的內容顯示在我上傳的圖片上。

我想做的是使數據看起來像下面的樣子

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數據使數據結構像這樣呢?

我認為應該這樣做。

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])

使用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.]])
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])
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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM