簡體   English   中英

蟒蛇。 ValueError無法將字符串轉換為float:

[英]Python. ValueError could not convert string to float:

我正在嘗試生成文本文件中指定列中數字的平均值。 我收到錯誤消息,python無法將字符串轉換為浮點數,盡管我看不到可以將無效字符串傳遞給哪里。

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

您正在將一個字符串傳遞給sum_lod()

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

data是一個字符串列表,然后data[col]是一個元素。

sum_data()期望可迭代

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

遍歷一個數字,然后為您提供各個字符:

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

暫無
暫無

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

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