2015-01-26 184 views
-1

我試圖在文本文件中的指定列中生成數字的平均值。我收到一個錯誤,蟒蛇無法將字符串轉換爲浮點數,儘管我沒有看到我可以傳遞一個無效字符串的位置。Python。 ValueError無法將字符串轉換爲浮點型:

def avg_col(f, col, delim=None, nhr=0): 
    """ 
    file, int, str, int -> float 

    Produces average of data stored in column col of file f 

    Requires: file has nhr header rows of data; data is separated by delim 

    >>> test_file = StringIO('0.0, 3.5, 2.0, 5.8, 2.1') 
    >>> avg_col(test_file, 2, ',', 0) 
    2.0 

    >>> test_file = StringIO('0.0, 3.5, 2.0, 5.8, 2.1') 
    >>> avg_col(test_file, 3, ',', 0) 
    5.8 
    """ 
    total = 0 
    count = 0 


    skip_rows(f, nhr) 
    for line in f: 
     if line.strip() != '': 
      data = line.split(delim) 
      col_data = data[col] 
      total = sum_data(col_data) + total 
      count = len(col_data) + count 
    return total/count 

def sum_data(lod): 
    ''' 
    (listof str) -> Real 

    Consume a list of string-data in a file and produce the sum 

    >>> sum_data(['0']) 
    0.0 
    >>> sum_data(['1.5']) 
    1.5 

    ''' 
    data_sum = 0 
    for number in lod: 
     data_sum = data_sum + float(number) 
    return data_sum 
+3

你需要共享的完整追蹤,如果你可以提供一些重現異常的示例數據,這比僅發佈的代碼更有幫助。 – 2015-01-26 20:24:10

回答

2

您傳遞一個字符串sum_lod()

data = line.split(delim) 
col_data = data[col] 
total = sum_data(col_data) + total 

data是一個字符串列表,data[col]然後一個元素。在若干

def sum_data(lod): 
    # ... 
    for number in lod: 

迭代然後給你的單個字符:

在另一方面sum_data()期望一個迭代

>>> for element in '5.8': 
...  print element 
... 
5 
. 
8 

試圖把這樣的字符串中的每個元素可以很容易導致您試圖將而不是號碼的字符轉換爲浮點數:

>>> float('.') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: could not convert string to float: . 

無論是傳遞一個字符串的列表

total += sum_data([col_data]) 
count += 1 

或只是一個元素上使用float()您有:

total += float(col_data) 
count += 1 
相關問題