這串數據有什么方法用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. docker容器呢SSH為什么連不通呢?2. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””3. docker網絡端口映射,沒有方便點的操作方法么?4. nignx - docker內nginx 80端口被占用5. debian - docker依賴的aufs-tools源碼哪里可以找到???6. 前端 - ng-view不能加載進模板7. android clickablespan獲取選中內容8. python - from ..xxxx import xxxx到底是什么意思呢?9. javascript - iframe 為什么加載網頁的時候滾動條這樣顯示?10. angular.js - ng-grid 和tabset一起用時,grid width默認特別小
