怎样用 Python 转换这段代码

2021-03-08 23:14:14 +08:00
 aparty
源代码:
[
{"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"}
]

求实现方法
2292 次点击
所在节点    Python
6 条回复
wuwukai007
2021-03-08 23:48:25 +08:00
import pandas as pd
from pandas.io.json import json_normalize
json_normalize(a,'tags',['userid']).drop('type',axis=1).to_dict('records')
如果觉得有用,请务必回复我,不然我会伤心的😥
Macv1994
2021-03-08 23:54:06 +08:00
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)
```
DGideas
2021-03-09 00:15:08 +08:00
dll30
2021-03-09 21:21:50 +08:00
我愣是没看懂你想怎么转,给个说明呀
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)
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/759787

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX