Python | 包含元组的列表转 JSON,更好的做法? - V2EX
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
oddcc

Python | 包含元组的列表转 JSON,更好的做法?

  •  
  •   oddcc Nov 29, 2016 3078 views
    This topic created in 3450 days ago, the information mentioned may be changed or developed.

    原始数据是一个由元组构成的列表,每个元组包含年、月 P 级、数量,要转换成 JSON ,具体示例如下:

    # 原始数据 rs=[(2016,1,'p0',1),(2016,2,'p1',2),(2016,2,'p2',3),(2016,3,'p3',25),(2016,4,'p4',55)] # 目标 JSON ,如果某月没有相应的 P 级的数据,要补 0 {'p2': [0, 3, 0, 0], 'p3': [0, 0, 25, 0], 'p0': [1, 0, 0, 0], 'p1': [0, 2, 0, 0], 'p4': [0, 0, 0, 55], 'categories': ['2016-1', '2016-2', '2016-3', '2016-4']} 

    下面是我的做法,是把数据先转换为 dict ,然后在遍历生成 JSON 的时候通过 setdefault 把缺失的数据补 0 。但是感觉很笨,不知道更好的做法是什么?

    # coding=utf-8 rs=[(2016,1,'p0',1),(2016,2,'p1',2),(2016,2,'p2',3),(2016,3,'p3',25),(2016,4,'p4',55)] # 预处理,把 rs 转换为字典 dict1 = {} for (year, month, p_level, count) in rs: dict1.setdefault(year,{}) dict1[year].setdefault(month,{}) dict1[year][month].setdefault(p_level,{}) dict1[year][month][p_level] = count # dict1 >> {2016: {1: {'p0': 1}, 2: {'p2': 3, 'p1': 2}}} # 预处理,取年份月份和 P 级的集合,这样数据有变化也可以处理 p_levels = [] mOnths= [] years = [] for i in rs: if i[0] not in years: years.append(i[0]) if i[1] not in months: months.append(i[1]) if i[2] not in p_levels: p_levels.append(i[2]) months.sort() years.sort() result={} result['categories']=[str(year)+'-'+str(month) for year in years for month in months] for p_level in p_levels: for month in months: result.setdefault(p_level,[]).append(dict1[2016][month].get(p_level, 0)) print result # {'p2': [0, 3, 0, 0], # 'p3': [0, 0, 25, 0], # 'p0': [1, 0, 0, 0], # 'p1': [0, 2, 0, 0], # 'p4': [0, 0, 0, 55], # 'categories': ['2016-1', '2016-2', '2016-3', '2016-4']} 
    2 replies    2016-11-29 18:38:27 +08:00
    Bryan8
        1
    Bryan8  
       Nov 29, 2016   1
    ```Python
    rs = [(2016, 1, 'p0', 1), (2016, 2, 'p1', 2), (2016, 2, 'p2', 3),
    (2016, 3, 'p3', 25), (2016, 4, 'p4', 55)]

    dic = {'categories': []}

    mOnth= max([i[1] for i in rs])


    for i in rs:
    dic.setdefault(i[2], [0 for j in range(month)])
    dic[i[2]][i[1] - 1] = i[3]
    dic['categories'].append(str(i[0]) + '-' + str(i[1]))

    print(dic)
    ```

    这样?
    oddcc
        2
    oddcc  
    OP
       Nov 29, 2016
    @Bryan8 谢谢回复,确实应该把预处理做的彻底一点,先全部初始化成 0 再填数据就好了…
    About     Help     Advertise     Blog     API     FAQ     Solana     1035 Online   Highest 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 41ms UTC 22:38 PVG 06:38 LAX 15:38 JFK 18:38
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86