消息关闭
    暂无新消息!
[('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': '李四'}]

这样的格式,有什么还得方法吗?想了好久想不到有效的做法。


3个回答

︿ 2

這種情況應該使用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 pd
df = 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變成list
print ( [{'data':list(d.loc[x].values.tolist()) , 'name': x} for x in set(d.index) ] )   

最後一行就是你要的結果。基本上就是用倒數第三行索引結果為列表推導基礎,產出你要的字典,內有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
from collections import defaultdict

d = 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()]
︿ 1
# python2
# coding: utf8
a = [('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