代码之家  ›  专栏  ›  技术社区  ›  zipline86

如何使用try和except防止for循环停止[关闭]

  •  -2
  • zipline86  · 技术社区  · 7 年前

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

    我做了一个if-elif语句,但无法使其工作。我试着编写代码,如果list==None,那么做一些elif做一些别的。但似乎没有一个不起作用。

    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]
    
    4 回复  |  直到 7 年前
        1
  •  1
  •   toti08    7 年前

    在python中,通常尝试做一些事情,然后处理抛出的异常(如果有的话)。在您的情况下,我首先尝试从列表中读取并捕获抛出的异常,如下所示:

    try:
        result = sample_here['description']['captions'][0]        
    except IndexError:
        result = sample_here['description']['tags'][0]
    

    try except 阻止。

        2
  •  3
  •   Amy Chou    7 年前

    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
    
        3
  •  0
  •   U13-Forward    7 年前

    好像是伪代码。

    if not sample['captions']:
        result = sample['description']['tags'][0]
    else:
        result = sample['description']['captions'][0]
    

    即使我不知道 sample_here

    def f(sample):
        if not sample['description']['captions']:
            result = sample['description']['tags'][0]
        else:
            result = sample['description']['captions'][0]
        return result
    

    然后我们可以做:

    print(f(sample1))
    

    或:

    print(f(sample2))
    

    然后得到你想要的输出

        4
  •  0
  •   bruno desthuilliers    7 年前

    你的要求基本上是检查清单是否是空的,

    这可以简单地通过一个pythonic的方式来实现:

     if not a: 
         print("a is empty")
    

    希望有帮助。