列表中的列表如何访问elemen

2024-10-02 20:32:44 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

def liveGame(summonerName):
req = requests.get('https://br1.api.riotgames.com/lol/spectator/v3/active-games/by-summoner/' + str(summonerName) + '?api_key=' + apikey)
req_args = json.loads(req.text)
print(req_args)

这就是我从我的朋友那里得到的请求.get地址:

{
    'gameId': 1149933395,
    'mapId': 11,
    'participants': [
        {
            'teamId': 100,
            'spell1Id': 11,
            'spell2Id': 4,
            'championId': 141,
            'profileIconId': 7,
            'summonerName': 'Disneyland Party',
            ...
        }
    ]
}

我简化了请求的返回,但是正如您所看到的,“参与者”索引是另一个列表。那么,如何访问此列表的内容(teamId、Spell1Id等)?你知道吗

我只能通过以下方式访问完整列表:

print(req_args['participants'])

但是,我只想访问“参与者”列表中的一个元素。你知道吗

我使用的是python3.6。你知道吗


Tags: httpsapi密码列表getdefargs参与者
2条回答

您可以像访问普通列表一样使用索引访问此列表项 如果要访问req_args['participants']的第一个元素,可以使用

req_args['participants'][i]

其中i只是您要从列表中访问的项的索引。你知道吗

由于链表中的项目是字典,只能访问一个项目(在本例中是第一个项目)的teamId和spellId,所以您可以执行以下操作

req_args['participants'][0]['teamId']
req_args['participants'][0]['spell1Id']

您还可以遍历列表来访问每个字典以及teamId、spell1Id或字典中的其他键的值

for participant in req_args['participants']:
    print(participant['teamId'])
    print(participant['spell1Id'])

从dictionary对象获取值很简单。你知道吗

打印项目['participants'][0].get('teamId')

打印项目['participants'][0].get('spell1Id')

相关问题 更多 >