使用get()列出索引超出范围

2024-04-26 03:01:16 发布

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

我得到一个错误'list' object has no attribute 'get'。通常,效果很好

weather_1D_ago = data['city']['weather']['daily'][0]['actual']['fmt']
weather_2D_ago = data['city']['weather']['daily'][1]['actual']['fmt']

'city': {'weather': {'daily': [{'actual': {'fmt': '1.2',
                                           'raw': 1.2},
                                'date': '1D_ago',
                                'estimate': {'fmt': '1.3',
                                             'raw': 1.3}},
                               {'actual': {'fmt': '2.2',
                                           'raw': 2.2},
                                'date': '2D_ago',
                                'estimate': {'fmt': '2.3',
                                             'raw': 2.3}},,

直到路径丢失,如下所示:

'city': {'weather': {'daily': []},

更新:我尝试使用.get()来获取数据,如果缺少值,则使其返回为None。你知道吗

weather_1D_ago = data['city']['weather'].get('daily', {})[0].get('actual', {}).get('fmt', {})
weather_2D_ago = data['city']['weather'].get('daily', {})[1].get('actual', {}).get('fmt', {})

但我刚得到一个错误list index out of range

我应该避免使用try-except块,因为当引用weather_1D_ago时,它会混淆我的其他代码,并且会生成另一个错误:local variable 'weather_1D_ago' referenced before assignment

那么,即使路径无效,如何让它使用.get()返回None?谢谢!你知道吗


Tags: 路径nonecitydatagetdateraw错误
1条回答
网友
1楼 · 发布于 2024-04-26 03:01:16
def safe_list_get(l, i):
    if l and i < len(l):
        return l[i]
    return {}

weather_1D_ago = safe_list_get(data['city']['weather'].get('daily', []),0).get('actual', {}).get('fmt', {})
weather_2D_ago = safe_list_get(data['city']['weather'].get('daily', []),1).get('actual', {}).get('fmt', {})

相关问题 更多 >