2017-02-14 125 views
-2

我有一個CSV文件和數據文件的格式:讀一個CSV文件將字符串轉換爲浮動

行1:

[-0.74120803 0.6338942 ],[-1.01583889 0.20901699],[-1.02969154 0.14459244],[ 0.10362657 0.31347394],[ 1.69977092 -0.13384537],[ 1.39789431 -0.52155783],[ 0.02928792 0.24156825],[-1.03616494 0.33943 ],[ 0.84921822 0.47879992],[ 0.279905 0.96184517],[ 0.43602597 -0.27275052],[ 1.4766132 -0.48128695],[ 0.96219625 -0.44950686],[ 0.24356381 -0.0253022 ],[ 0.09346193 0.07808998],[ 0.26571546 -0.1678716 ],[ 0.03055046 1.05913456],[ 1.94137487e+00 -1.57339675e-03],[ 0.22311559 0.98762516],[ 2.00176133 0.13017485],...... 

注意,數據是兩行:第一行包含x和y座標,第二行包含它們的標誌狀態。

行2

0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,1,0,1,0,1,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,0,0,1,0,1,1,0,0,0,1,1,1,1,0,1,0,0,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,1,1,....... 

我想將數據存儲在3所列出:xyflag。 感謝您對此部分的幫助。

+5

請發佈一些您已經開始使用的代碼,以及您遇到的確切問題,以便我們可以幫助您進行調試。 –

+0

引用與代碼格式有很大區別 – Dan

+0

您使用的Python版本是2或3? – martineau

回答

1
row1 = '[-0.74120803 0.6338942 ],[-1.01583889 0.20901699],[-1.02969154 0.14459244],[ 0.10362657 0.31347394],[ 1.69977092 -0.13384537],[ 1.39789431 -0.52155783],[ 0.02928792 0.24156825],[-1.03616494 0.33943 ],[ 0.84921822 0.47879992],[ 0.279905 0.96184517],[ 0.43602597 -0.27275052],[ 1.4766132 -0.48128695],[ 0.96219625 -0.44950686],[ 0.24356381 -0.0253022 ],[ 0.09346193 0.07808998],[ 0.26571546 -0.1678716 ],[ 0.03055046 1.05913456],[ 1.94137487e+00 -1.57339675e-03],[ 0.22311559 0.98762516],[ 2.00176133 0.13017485]' 
row2 = '0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,1,0,1,0,1' 

l = [] 

for xy, flag in zip(row1.split(','), row2.split(',')): 
    x, y = xy.strip('[] ').split(' ') 
    l.append((float(x), float(y), int(flag))) 

print l 

如果您prefere 3名獨立的名單:

row1 = '[-0.74120803 0.6338942 ],[-1.01583889 0.20901699],[-1.02969154 0.14459244],[ 0.10362657 0.31347394],[ 1.69977092 -0.13384537],[ 1.39789431 -0.52155783],[ 0.02928792 0.24156825],[-1.03616494 0.33943 ],[ 0.84921822 0.47879992],[ 0.279905 0.96184517],[ 0.43602597 -0.27275052],[ 1.4766132 -0.48128695],[ 0.96219625 -0.44950686],[ 0.24356381 -0.0253022 ],[ 0.09346193 0.07808998],[ 0.26571546 -0.1678716 ],[ 0.03055046 1.05913456],[ 1.94137487e+00 -1.57339675e-03],[ 0.22311559 0.98762516],[ 2.00176133 0.13017485]' 
row2 = '0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,1,0,1,0,1' 

listX, listY = [], [] 

for xy in row1.split(','): 
    x, y = xy.strip('[] ').split(' ') 
    listX.append(float(x)) 
    listY.append(float(y)) 

listFlag = [int(flag) for flag in row2.split(',')] 

print listX, listY, listFlag 
1

兩個單行會做:

flags = [int(x) for x in row2.split(',')] 
x, y = zip(*((float(value) for value in entry[1:-1].split()) for entry in row1.split(','))) 

現在:

print(flags[:5]) 
print(list(x[:5])) 
print(list(y[:5])) 

輸出:

[0, 0, 0, 1, 1] 
[-0.74120803, -1.01583889, -1.02969154, 0.10362657, 1.69977092] 
[0.6338942, 0.20901699, 0.14459244, 0.31347394, -0.13384537] 
相關問題