Error increase if a line is not specified in one or more lists

I want to raise the error manually if target_string does not occur in one or more lists of the list of lists.

if False in [False for lst in lst_of_lsts if target_string not in lst]:
    raise ValueError('One or more lists does not contain "%s"' % (target_string))

Of course, there is a more pythonic solution than the above.

+4
source share
2 answers

Use all()

if not all(target_string in lst for lst in lst_of_lsts):
    raise ValueError('One or more lists does not contain "%s"' % (target_string))

The generator gives Trueeither Falsefor each individual test, and all()checks whether they are all true. Since we use a generator, the estimate is lazy, that is, it stops when the first one is Falsefound without evaluating the full list.

Or if double inon the same label seems confusing, you can

if not all((target_string in lst) for lst in lst_of_lsts):
    raise ValueError('One or more lists does not contain "%s"' % (target_string))

, .

+9

:

for lst in lst_of_lsts :
   if target_string not in lst : 
      raise ValueError('At least one  list does not contain "%s"' % (target_string))
0

Source: https://habr.com/ru/post/1627601/


All Articles