2016-08-01 55 views
1

我無法處理將字符串列表拆分爲浮點列表的問題。我打開一個文本文件(.vol,但它只是包含文本),最後一行是非常長的一行數字。將字符串列表拆分爲浮點數 - 內存錯誤

Params1 437288.59375000 102574.20312500 -83.30001831
Params2 437871.93750000 104981.40625000 362.10000610
Params3 0.00000000
Params4 342 1416 262
Params5 583.34375000 2407.19995117 445.40002441
Params6 20.00000000
Params7 1.70000005
Params8 126879264個
值:
0.25564435 0。 462439 0.1365 0.1367 26.00000000(等等,還有數以百萬計值)

因爲它是一個txt文件的10日線,我將它們加載到一個列表:

with open('d:/py/LAS21_test.vol') as f: 
txt = [] 
for line in f: 
    txt.append(line) 

然後我試着轉換從字符串彩車通過:

A = [] 
for vx in txt[9]: 
    try: 
     A.append(float(vx)) 
    except ValueError: 
     pass 
print (A[0:20]) 
print (txt[9][0:20]) 

這給我的結果:

[0.0, 2.0, 5.0, 5.0, 6.0, 4.0, 4.0, 3.0, 5.0, 0.0, 4.0, 6.0, 2.0, 4.0, 3.0, 9.0, 0.0, 1.0, 3.0, 6.0] 
0.25564435 0.462439 

我想有是正確拆分花車的列表,如:

[0.25564435, 0.462439] 

我以前except ValueError忽略空格 - 當只用float(txt[9])我得到的值錯誤。 第二個問題:我不能使用txt[9].split,因爲那時我得到'內存錯誤'。

我該如何將其轉換爲正確的浮動列表?

+0

如果要在添加的輸入文件的內容更容易理解。 – AntoineB

+0

剛剛添加,謝謝。 –

回答

0

如果我理解正確,不能使txt [9] .split()像這樣映射:map(float, txt[9].split())因爲txt [9]太大。

你可以試試這個發生器:

def float_generator(txt): 
     x = '' 
     for c in txt: 
      if c != ' ': 
       x += c 
      else: 
       out = float(x) 
       x = '' 
       yield(out) 

for i in float_generator(txt[9]): 
     print (i) 
0

這裏(如在評論中提到的)是你的問題:

1)在你試圖字符串索引拆分之前,你正試圖空間轉換爲浮動第一種情況下(因此ValueError

2)在第二種情況下,列表中可能有太多數字,並且您正在使用一大串大字符串填充內存(因此爲MemoryError)。

請先嚐試:

numbers = [float(s) for s in txt[9].split(' ')] 

這應該給你號碼列表。如果這也導致MemoryError,你就必須手動遍歷字符串:

numbers = [] 
numstring = [] 
for s in txt[9] 
    # Reached a space 
    if s == ' ': 
     numbers.append(float(numstring)) 
     numstring = [] 
    else: 
     numstring.append(s) 

這將是慢得多,但將節省內存。