V2EX = way to explore
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
aparty
V2EX  ›  Python

怎样用 Python 转换这段代码

  •  
  •   aparty · 2021-03-08 23:14:14 +08:00 · 2295 次点击
    这是一个创建于 1356 天前的主题,其中的信息可能已经有所发展或是发生改变。
    源代码:
    [
    {"userid":"Change","tags":[{"type":1,"tag_id":"e" }],},
    {"userid":"andy.lei","tags":[{"type":1,"tag_id":"eg" },{"type":1,"tag_id":"ti"}],}
    ]

    希望用 python 处理后变成:
    [
    {"userid":"change","tagid":"e"},{"userid":"andy.lei","tagid":"eg"},{"userid":"andy.lei","tagid":"ti"}
    ]

    求实现方法
    6 条回复    2021-03-10 12:27:29 +08:00
    wuwukai007
        1
    wuwukai007  
       2021-03-08 23:48:25 +08:00   ❤️ 4
    import pandas as pd
    from pandas.io.json import json_normalize
    json_normalize(a,'tags',['userid']).drop('type',axis=1).to_dict('records')
    如果觉得有用,请务必回复我,不然我会伤心的😥
    Macv1994
        2
    Macv1994  
       2021-03-08 23:54:06 +08:00
    DGideas
        3
    DGideas  
       2021-03-09 00:13:27 +08:00
    上边的方法都不太好哇。。。

    ```python
    a = [
    {"userid":"Change","tags":[{"type":1,"tag_id":"e" }],},
    {"userid":"andy.lei","tags":[{"type":1,"tag_id":"eg" },{"type":1,"tag_id":"ti"}],}
    ]

    result = []
    [*map(lambda x: result.extend([{"userid": x["userid"], "tagid": tag["tag_id"]} for tag in x["tags"]]), a)]
    print(result)
    ```
    dll30
        5
    dll30  
       2021-03-09 21:21:50 +08:00
    我愣是没看懂你想怎么转,给个说明呀
    cbiqih
        6
    cbiqih  
       2021-03-10 12:27:29 +08:00
    ```python
    users = [
    {"userid": "Change", "tags": [{"type": 1, "tag_id": "e"}], },
    {"userid": "andy.lei", "tags": [{"type": 1, "tag_id": "eg"}, {"type": 1, "tag_id": "ti"}], }
    ]

    result = [{'userid': user['userid'], 'tagid': tag['tag_id']} for user in users for tag in user['tags']]
    print(result)
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2833 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 08:48 · PVG 16:48 · LAX 00:48 · JFK 03:48
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.