列表排序
my_list = [["a",33],["b",55],["c",11]]
###基于带名函数的排序
def choose_sort_key(element):
return element[1]
my_list.sort(key=choose_sort_key,reverse=False)
print(my_list)
my_list.sort(key=lambda element:element[1],reverse=True)
print(my_list)
需求分析
from pyecharts.charts import Bar,Timeline
from pyecharts.options import *
###读取数据
f = open("D:/PythonContent/1960-2019全球GDP数据.csv","r",encoding="GB2312")
data_lines = f.readlines()
f.close()
#删除第一条数据
data_lines.pop(0)
data_dict={}
for line in data_lines:
year = int(line.split(",")[0])
country = line.split(",")[1]
gdp = float(line.split(",")[2])
try:
data_dict[year].append([country,gdp])
except KeyError:
data_dict[year] = []
data_dict[year].append([country,gdp])
print(data_dict)
####时间线对象
timeline = Timeline()
######排序年份 sorted 排序
sorted_year_list = sorted((data_dict.keys()))###获取字典所有键值
#####def get_second_element(element):
###### return element[1]
for year in sorted_year_list:
data_dict[year].sort(key = lambda element:element[1],reverse=True)
print(data_dict[year])
year_data =data_dict[year][0:8]
x_data = []
y_data = []
for country_gdp in year_data:
x_data.append(country_gdp[0])
y_data.append(country_gdp[1]/100000000)
bar = Bar()
x_data.reverse()
y_data.reverse()
bar.add_xaxis(x_data)
bar.add_yaxis("GDP(亿)",y_data,label_opts=LabelOpts(position ="right"))
bar.reversal_axis()
timeline.add(bar,str(year))
timeline.add_schema(
play_interval=1000,
is_timeline_show=True,
is_loop_play=False,
is_auto_play=True
)
timeline.render("1960-20119全球GDP全球前8.html")