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

如果列中不存在某个值,则停止代码执行

  •  0
  • lfox  · 技术社区  · 2 年前

    
    res = APAC['colA'].isin(['A','B','C','D','E','F','G','H'])
    try:
        for i in res:
            if i == False:
                print('Different response than present in the list')
    except Exception as e:
           print(e)
           raise
    

    简而言之,如果colA包含除A、B、C、D、E、F、G、H以外的任何其他值,则抛出一个错误并停止代码的进一步执行。

    1 回复  |  直到 2 年前
        1
  •  0
  •   Guy    2 年前

    您可以在打印时引发异常。你也不需要抓住它

    res = APAC['colA'].isin(['A','B','C','D','E','F','G','H'])
    for i, val in enumerate(res):
        if not val:
            raise Exception(f'Different response than present in the list in row {i}')
    

    故障时的输出:

    Traceback (most recent call last):
      File "test.py", line 19, in <module>
        raise Exception('Different response than present in the list')
    Exception: Different response than present in the list in row 6