首页 > 解决方案 > 如何使用 try 和 except 来防止 for 循环停止

问题描述

我有一堆样本是字典,其中一些值在列表中。我想从列表中检索信息,但有时列表中的某些键为空。我想要做的是检索某些值。我想声明,如果列表为空,则从不同的键中检索一个值。

我做了一个 if-elif 声明,但无法让它工作。我试图编写代码,如果 list==None 然后做一些事情 elif 做其他事情。似乎 None 不起作用。

我在下面举了一个我想要做的例子。

sample_1 = {'description' : {'captions': [],
                           'tags': ['person',
                                   'cat']}}
sample_2 = {'description' : {'captions': ['NOT an empty list'],
                           'tags': ['person',
                                   'cat']}}


# if captions list is empty then print first item in 'tags' list.
# else if the 'captions' list has an item then print that item 
if sample_here['captions']==None in sample_here:
    result = sample_here['description']['tags'][0]
elif 'captions' in sample_here:
    result = sample_here['description']['captions'][0]

标签: pythonif-statement

解决方案


空列表 [] 不等于 None。

sample_1 = {'description' : {'captions': [],
                           'tags': ['person',
                                   'cat']}}
sample_2 = {'description' : {'captions': ['NOT an empty list'],
                           'tags': ['person',
                                   'cat']}}
def get_captions(sample_here):
    # thanks to bruno desthuilliers's correction. [] has a bool value False
    if not sample_here['description']['captions']:
        result = sample_here['description']['tags'][0]
    else:
        result = sample_here['description']['captions'][0]
    return result

print(get_captions(sample_1))
print(get_captions(sample_2))

这输出:

person
NOT an empty list

推荐阅读