這串數據有什么方法用python輸出我想要的格式?
問題描述
[(’2016-09’, 20874.73, ’李四’), (’2016-10’, 64296.45, ’李四’), (’2016-11’, 58657.1, ’李四’), (’2016-12’, 51253.14, ’李四’), (’2017-01’, 57791.88, ’李四’), (’2017-01’, 46007.0, ’張三’), (’2017-02’, 67193.55, ’李四’), (’2017-02’, 38352.0, ’張三’), (’2017-03’, 83359.53, ’李四’), (’2017-03’, 49661.0, ’張三’), (’2017-04’, 39907.0, ’張三’)]
上面這串數據我想輸出格式為
[{’data’: [[’2013-04’, 52.9], [’2013-05-01’, 50.7]], ’name’: ’張三’},{’data’: [[’2013-04’, 27.7], [’2013-05-01’, 25.9]], ’name’: ’李四’}]
這樣的格式,有什么還得方法嗎?想了好久想不到有效的做法。
問題解答
回答1:# python2# coding: utf8a = [(’2016-09’, 20874.73, ’李四’), (’2016-10’, 64296.45, ’李四’), (’2016-11’, 58657.1, ’李四’), (’2016-12’, 51253.14, ’李四’), (’2017-01’, 57791.88, ’李四’), (’2017-01’, 46007.0, ’張三’), (’2017-02’, 67193.55, ’李四’), (’2017-02’, 38352.0, ’張三’), (’2017-03’, 83359.53, ’李四’), (’2017-03’, 49661.0, ’張三’), (’2017-04’, 39907.0, ’張三’)]s = []for i in a: for dict_tmp in s:if dict_tmp.get(’name’, ’’) == i[2]: dict_tmp[’data’].append([i[0], i[1]]) break else:s.append( {’name’: i[2],’data’: [[i[0], i[1]]] })print s回答2:
from collections import defaultdictd = defaultdict(list)l_data = [(’2016-09’, 20874.73, ’李四’), (’2016-10’, 64296.45, ’李四’), (’2016-11’, 58657.1, ’李四’), (’2016-12’, 51253.14, ’李四’), (’2017-01’, 57791.88, ’李四’), (’2017-01’, 46007.0, ’張三’), (’2017-02’, 67193.55, ’李四’), (’2017-02’, 38352.0, ’張三’), (’2017-03’, 83359.53, ’李四’), (’2017-03’, 49661.0, ’張三’), (’2017-04’, 39907.0, ’張三’)]for x in l_data: d[x[2]].append([x[0], x[1]])result = [{’name’: k, ’data’: v} for k, v in d.iteritems()]回答3:
這種情況應該使用pandas模塊比較永續:
data_input = [(’2016-09’, 20874.73, ’李四’), (’2016-10’, 64296.45, ’李四’), (’2016-11’, 58657.1, ’李四’), (’2016-12’, 51253.14, ’李四’), (’2017-01’, 57791.88, ’李四’), (’2017-01’, 46007.0, ’張三’), (’2017-02’, 67193.55, ’李四’), (’2017-02’, 38352.0, ’張三’), (’2017-03’, 83359.53, ’李四’), (’2017-03’, 49661.0, ’張三’), (’2017-04’, 39907.0, ’張三’)]import pandas as pddf = pd.DataFrame(data_input)df.columns = [’month’,’value’,’name’]d = df.set_index([’name’])print ( set(d.index) ) # {’張三’, ’李四’}print ( list(d.loc[’張三’].values.tolist()) ) # data變成listprint ( [{’data’:list(d.loc[x].values.tolist()) , ’name’: x} for x in set(d.index) ] )
最後一行就是你要的結果?;旧暇褪怯玫箶档谌兴饕Y果為列表推導基礎,產出你要的字典,內有name及data,而data有列表出的數據
[{’data’: [[’2016-09’, 20874.73], [’2016-10’, 64296.45], [’2016-11’, 58657.1], [’2016-12’, 51253.14], [’2017-01’, 57791.88], [’2017-02’, 67193.55], [’2017-03’, 83359.53]], ’name’: ’李四’}, {’data’: [[’2017-01’, 46007.0], [’2017-02’, 38352.0], [’2017-03’, 49661.0], [’2017-04’, 39907.0]], ’name’: ’張三’}]
如果有更多數據處理的需要,真的很推薦把pandas模塊學起來。
相關文章:
1. python - django 里自定義的 login 方法,如何使用 login_required()2. android-studio - Android 動態壁紙LayoutParams問題3. sql語句如何按or排序取出記錄4. angular.js - 不適用其他構建工具,怎么搭建angular1項目5. 主從備份 - 跪求mysql 高可用主從方案6. python如何不改動文件的情況下修改文件的 修改日期7. mysql優化 - mysql count(id)查詢速度如何優化?8. css3 - [CSS] 動畫效果 3D翻轉bug9. mysql主從 - 請教下mysql 主動-被動模式的雙主配置 和 主從配置在應用上有什么區別?10. node.js - node_moduls太多了
