如题
完整代码:
import json
import pygal
import math
from itertools import groupby
file_name = 'btc_close_2017.json'
with open(file_name) as f:
btc_data = json.load(f)
dates, months, weeks, weekdays, closes = [], [], [], [], [], []
for btc_dict in btc_data:
dates.append(btc_dict['date'])
months.append(int(btc_dict['month']))
weeks.append(int(btc_dict['week']))
weekdays.append(btc_dict['weekday'])
closes.append(int(float(btc_dict['close'])))
line_chart = pygal.Line(x_label_rotation=20, show_minor_x_labels=False)
line_chart.title = '收盘价(¥)'
line_chart.x_labels = dates
N = 20
line_chart.x_labels_major = dates[::N]
def draw_line(x_data, y_data, title, y_legend):
xy_map = []
for x, y in groupby(sorted(zip(x_data, y_data)), key=lambda _: _[0]): # 2
y_list = [v for _,v in y]
xy_map.append([x, sum(y_list) / len(y_list)]) # 3
x_unique, y_mean = [*zip(*xy_map)] # 4
line_chart = pygal.Line()
line_chart.title = title
line_chart.x_labels = x_unique
line_chart.add(y_legend, y_mean)
line_chart.render_to_file(title + '.svg')
return line_chart
idx_month = dates.index('2017-12-01')
line_chart_month = draw_line(months[:idx_month], closes[:idx_month],'收盘价月日均值(¥)', '月日均值')
line_chart_month
运行的时候,报错,TypeError: object of type 'int' has no len()。 我把最后3行删掉,运行的时候没有错误,所以这个len()错误,感觉像是倒数第二行的值的问题?closes是int类型,不能使用len()函数? 想了半个下午不知道怎么做。
我把书上的源代码copy进去也是一样的报错。
那位大佬给解答下,非常感谢!!
完整代码:
import json
import pygal
import math
from itertools import groupby
file_name = 'btc_close_2017.json'
with open(file_name) as f:
btc_data = json.load(f)
dates, months, weeks, weekdays, closes = [], [], [], [], [], []
for btc_dict in btc_data:
dates.append(btc_dict['date'])
months.append(int(btc_dict['month']))
weeks.append(int(btc_dict['week']))
weekdays.append(btc_dict['weekday'])
closes.append(int(float(btc_dict['close'])))
line_chart = pygal.Line(x_label_rotation=20, show_minor_x_labels=False)
line_chart.title = '收盘价(¥)'
line_chart.x_labels = dates
N = 20
line_chart.x_labels_major = dates[::N]
def draw_line(x_data, y_data, title, y_legend):
xy_map = []
for x, y in groupby(sorted(zip(x_data, y_data)), key=lambda _: _[0]): # 2
y_list = [v for _,v in y]
xy_map.append([x, sum(y_list) / len(y_list)]) # 3
x_unique, y_mean = [*zip(*xy_map)] # 4
line_chart = pygal.Line()
line_chart.title = title
line_chart.x_labels = x_unique
line_chart.add(y_legend, y_mean)
line_chart.render_to_file(title + '.svg')
return line_chart
idx_month = dates.index('2017-12-01')
line_chart_month = draw_line(months[:idx_month], closes[:idx_month],'收盘价月日均值(¥)', '月日均值')
line_chart_month
运行的时候,报错,TypeError: object of type 'int' has no len()。 我把最后3行删掉,运行的时候没有错误,所以这个len()错误,感觉像是倒数第二行的值的问题?closes是int类型,不能使用len()函数? 想了半个下午不知道怎么做。
我把书上的源代码copy进去也是一样的报错。
那位大佬给解答下,非常感谢!!