如何在try/except循环中生成条件?

2024-03-28 14:04:46 发布

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

我在两个json文件上收集数据。你知道吗

第一个有一些我可以收集的数据。你知道吗

第二个没有所需的数据。我想把“娜”储存起来。你知道吗

我的问题是我不知道如何在脚本中正确地存储我的'NA'。你知道吗

这是我的密码:

import requests

# this is our profile ids
profile=['kaid_896965538702696832878421','kaid_1143236333220233567674383']

# prepare the list to get data
badgechall=[]

# do this for each profile id
for kaid in profile:
    # request the api link of the profile
    data = requests.get('https://www.khanacademy.org/api/internal/user/{}/profile/widgets?lang=en&_=190424-1429-bcf153233dc9_1556201931959'.format(kaid)).json()

    # go through each json file to get the data
    for item in data:
        # try to find on each dictionary of the list the desired data or pass
        try:
            for badges in item['renderData']['badgeCountData']['counts']:
                if badges['typeLabel'] == 'Challenge Patches':
                    badgechall.append(badges['count'])
        except KeyError:
            pass

print(badgechall)

当我运行这个代码时,我得到: [100]

我想得到的是: [100, 'NA']

'100'对应于第一个配置文件'kaid_896965538702696832878421''NA'对应于第二个配置文件'kaid_1143236333220233567674383'。你知道吗

我想有第一和第二个链接的数据,如果没有返回'NA'。所以我们应该有一个只有2个值的列表。你知道吗

我试过:

except KeyError:
    badgechall.append('NA')
    pass

但它的回报是: [100, 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA']


Tags: theto数据injsonfordataget
2条回答

您可以定义一个函数并从该函数返回第一个计数,或"NA"。你知道吗

def get_badge_count(data, badge='Challenge Patches'):
    for item in data:
        try:
            for badges in item['renderData']['badgeCountData']['counts']:
                if badges['typeLabel'] == badge:
                    return badges['count']
        except KeyError:
            pass
    return "NA"

for kaid in profile:
    data = requests.get('https://www.khanacademy.org/api/internal/user/{}/profile/widgets?lang=en&_=190424-1429-bcf153233dc9_1556201931959'.format(kaid)).json()
    badgechall.append(get_badge_count(data))

之后,badgechall就是[100, 'NA']。如果要匹配另一个标记,可以将其作为参数提供,例如get_badge_count(data, 'Sun Patches')

你是说你想跳出for循环吗?你知道吗

        except KeyError:
            badgechall.append('NA')
            break

相关问题 更多 >