站点图标 谷姐靓号网

python 的 list 怎么匹配 json 啊-meta

Rate this post

genre_movie = '{"genres":[{"id":28,"name":"动作"},{"id":12,"name":"冒险"},{"id":16,"name":"动画"},{"id":35,"name":"喜剧"},{"id":80,"name":"犯罪"},{"id":99,"name":"纪录"},{"id":18,"name":"剧情"},{"id":10751,"name":"家庭"},{"id":14,"name":"奇幻"},{"id":36,"name":"历史"},{"id":27,"name":"恐怖"},{"id":10402,"name":"音乐"},{"id":9648,"name":"悬疑"},{"id":10749,"name":"爱情"},{"id":878,"name":"科幻"},{"id":10770,"name":"电视电影"},{"id":53,"name":"惊悚"},{"id":10752,"name":"战争"},{"id":37,"name":"西部"}]}'

genre_ids = [80, 9648, 53]

想匹配生成genre_ids = [犯罪, 悬疑, 惊悚]

应该怎么写啊

热议
推荐楼 falomsc 3小时前

import json
import pandas as pd

genre_movie = '{"genres":[{"id":28,"name":"动作"},{"id":12,"name":"冒险"},{"id":16,"name":"动画"},{"id":35,"name":"喜剧"},{"id":80,"name":"犯罪"},{"id":99,"name":"纪录"},{"id":18,"name":"剧情"},{"id":10751,"name":"家庭"},{"id":14,"name":"奇幻"},{"id":36,"name":"历史"},{"id":27,"name":"恐怖"},{"id":10402,"name":"音乐"},{"id":9648,"name":"悬疑"},{"id":10749,"name":"爱情"},{"id":878,"name":"科幻"},{"id":10770,"name":"电视电影"},{"id":53,"name":"惊悚"},{"id":10752,"name":"战争"},{"id":37,"name":"西部"}]}'
df = pd.DataFrame(json.loads(genre_movie).get('genres'))

def get_genre_ids(genre_ids_in: list) -> list:
genre_ids_out = [df[df.id == i].iat[0, 1] for i in genre_ids_in] return genre_ids_out

推荐楼 NP_Prob 3小时前

json genre_movie到dict,然后在key "genres"下是一个list,这个list里面每个又是一个dict,每个dict有两个key,一个是"id",一个是"name",你可以用"id"做key,用"name"做value,再弄个新的dict,new_dict = {"28": "动作", ..., "37": "西部"},最后genre_ids = [80, 9648, 53],就可以有genre_name = [new_dict[genre_ids[0]], new_dict[genre_ids[1]]...],当然最后一步你可以写个函数处理了。

2楼 喵喵喵嗷 4小时前

key/value反转呗

3楼 zenk 4小时前

遍历呗

4楼 pathletboy 4小时前

先用json生成字典

5楼 yy10112001 3小时前

正则提取出来。

8楼 meta 3小时前

import json
import pandas as pd

这个是不是整复杂了。。。

然后:

    dict_new = dict(zip(df['id'],df['name']))

或者可以这样:

    dict_new = df.set_index('id').to_dict()['name']

开始没想到pandas

又学了个新方法:

    genre_ids = [80, 9648, 53]df.loc[df['id'].isin(genre_ids)]

输出:

    id name
    4 80 犯罪
    129648 悬疑
    16 53 惊悚

或者:

    genre_ids = [80, 9648, 53]df.loc[df['id'].isin(genre_ids)][['name']].to_dict('list')['name']

输出:

    ['犯罪', '悬疑', '惊悚']

申明:本文内容由网友收集分享,仅供学习参考使用。如文中内容侵犯到您的利益,请在文章下方留言,本站会第一时间进行处理。

退出移动版