What is the best way to check for several conditions? For example here:

if (name in line) and (age in line) and (string in text): do_something() 

If there are several ways, I would like to know where and when they are best to use.

  • 2
    The effectiveness of different methods will depend on the context of a specific task. For example, sometimes it will be more effective to use all([x in line for x in search_words_list]) , in other cases, to check the set intersection , etc. - MaxU
  • @MaxU: you put the brackets [] in vain — it changes the meaning of the expression ( if stack and stack[0] == value ). - jfs

3 answers 3

You can use all () for cases when it is necessary that all the conditions listed above and any () are satisfied, when it is necessary that at least one is executed.

For example, your code can be rewritten like this:

 if all([(name in line), (age in line), (string in text)]): do_something() 

This can be made more convenient if you first form an array of conditions, and then pass it to an if:

 checks = [name in line, age in line] checks.append(string in text) if all(checks): do_something() 

As you can see from this code, an array can be formed gradually by adding conditions in different places of the code, which can be useful when you need to generate a list of conditions dynamically depending on various external factors.

In addition, in functions, sometimes each condition is simply checked by individual if, and if the condition does not pass (or vice versa, depending on the task), then further execution is terminated by return:

 def foo(): if not(name in line): return False if not(age in line): return False if not(string in text): return False return True 
  • You can do a lot, but what is good about it, I did not understand. This is about any and all. - Qwertiy
  • @Qwertiy suppose we have a long chain of A and B and C and D or E and F... Or has crept into it. There is a chance not to notice it. And with all() there are no such chances. - Nick Volynkin
  • @Qwertiy is another plus - this is a more flexible way, it allows you not to know in advance how many conditions we are checking. - Nick Volynkin
  • @NickVolynkin, do not agree with the first paragraph. Yes, and with the second one - we calculate all the conditions, and then we check that all were true. In most cases, it is illogical. - Qwertiy
  • @NickVolynkin if there is no iterable, then all ([a, b, c]) is wrong: there is no short-circuit behavior, it looks less beautiful and less effective compared to (a and b and c) (split into several lines if necessary ). That is, the example from the question is degraded by using all (). For good, the question should be closed as too general: somewhere you obviously need to write conditions, somewhere you can use all (), somewhere you should use the Aho-Korasika algorithm (so that you can search for many words in the text simultaneously), for other data what other algorithms — it depends on a specific task — there are too many tasksjfs

The question is very, very general. Everything, in fact, depends on the task, for example, if you need to test the Syracuse hypothesis, then you use a for loop, and if or else or elif else . If the task requires branching in the algorithm, then just logical operators, if numerous conditions are checked, then use cycles.

  • one
    Все,собственно,зависит от задачи - exactly like that - MaxU
 text = '''1234\n567890''' line = '567890' keys = name, age, string = '5', '6', '78' # чем больше ключей в keys, тем длиннее запись условия ...and... if (name in line) and (age in line) and (string in line): print(1) # теперь длина условия не зависит от кол-ва keys check1 = [k in line for k in keys] if all(check1): # all для ...and... | any для ...or... print(2) # несколько разных условий можно объединить с помощью chain from itertools import chain check2 = string in text, line+age not in text if all(chain(check1, check2)): print(3) # или так if all(chain((k in line for k in keys), (string in text, line+age not in text))): print(4) # если условие сложное, его можно вынести в отдельную функцию def checker(key): return key in line or True # "сложное" условие # а при проверке использовать map if all(map(checker, keys)): print(5)