我很难理解为什么我在Python中得到这个TypeError

时间:2017-08-24 14:37:37

标签: python pygal

错误:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

当我的结果在我的Python代码中生成完美的浮点数时:

data = ",".join(str(x) for x in house_index_data)

0.12,0.29,0.13,0.12,0.23,0.13,0.07,0.21,0.22,0.18,0.11,0.18,0.16,0.07,0.20,
0.11,0.09,0.11,0.18,0.07,0.12,0.14,0.14,0.11,0.21,0.21,0.06,0.20,0.16,0.00,
0.14,0.12,0.04,0.10,0.12,0.13,0.11,0.21,0.22,0.08,0.11,0.12,0.08,0.00,0.13,
0.05,0.14,0.12,0.09,0.12,0.14,0.15,0.09,0.14,0.07,0.07,0.00,0.41,0.01,0.08,
0.08,0.09,0.10,0.21,...

@app.route('/main')
@login_required
def main():
    # Data from .csv file
    ######################
    base_dir = "db/"
    logged_in_user = g.user
    spreadsheet = pe.get_sheet(file_name=os.path.join(base_dir, "example.csv"))
    house_index_data = [x.encode('ascii') for x in spreadsheet.column[48]]
    print ",".join(str(x) for x in house_index_data)
    # data = str(house_index_data).replace("'", "")
    data = ",".join(str(x) for x in house_index_data)

    # Graphs (Bar) data
    #####################
    bar_chart = pygal.StackedBar(fill=True, interpolate='cubic', style=BlueStyle)
    bar_chart.title = 'Stack bar chart of House Index'
    bar_chart.add('House Index',  [data])
    bar_chart.render()

    return render_template('main.html',
                           user=logged_in_user,
                           value=spreadsheet,
                           bar_chart=bar_chart,
                           line_chart=line_chart)

2 个答案:

答案 0 :(得分:0)

Reference

此外,你多次做同样的事情;我指的是data = ",".join(str(x) for x in house_index_data)print ",".join(str(x) for x in house_index_data)

您只需打印data并删除print ",".join(str(x) for x in house_index_data)

即可

您的代码或多或少会如下所示:

@app.route('/main')
@login_required
def main():
    # Data from .csv file
    ######################
    base_dir = "db/"
    logged_in_user = g.user
    spreadsheet = pe.get_sheet(file_name=os.path.join(base_dir, "example.csv"))
    house_index_data = [x.encode('ascii') for x in spreadsheet.column[48]]
    # data = str(house_index_data).replace("'", "")
    data = ",".join(str(x) for x in house_index_data)
    print data

    # Graphs (Bar) data
    #####################
    bar_chart = pygal.StackedBar(fill=True, interpolate='cubic', style=BlueStyle)
    bar_chart.title = 'Stack bar chart of House Index'
    bar_chart.add('House Index',  [data])
    bar_chart.render()

    return render_template('main.html',
                           user=logged_in_user,
                           value=spreadsheet,
                           bar_chart=bar_chart,
                           line_chart=line_chart)

答案 1 :(得分:0)

看起来这就是问题所在:

house_index_data = [x.encode('ascii') for x in spreadsheet.column[48]]

house_index_data应为list of floats,您应该致电:

bar_chart.add('House Index', house_index_data)

所以也许:

house_index_data = [float(x.encode('ascii')) for x in spreadsheet.column[48]]
...
...
bar_chart.add('House Index', house_index_data)