How to check if list items are in a row

The reverse of this question (finding a string in a list) is so popular that I could not find the answer to my question.

black_list = ["ab:", "cd:", "ef:", "gh:"] for line in some_file: if ":" in line and black_list not in line: pass 

This obviously does not work. It should iterate over the list, which returns true / false, but I don't know how to do it elegantly. Thanks.

+4
source share
3 answers

The built-in any() function can help you:

 black_list = ["ab:", "cd:", "ef:", "gh:"] for line in some_file: if ":" in line and not any(x in line for x in black_list): pass 

You can also get the same effect with all() :

 for line in some_file: if ":" in line and all(x not in line for x in black_list): pass 

... but I think the first is closer to English, so it’s easier to follow.

+6
source

You can check each "flag" in the black list, as well as filter lines containing the black list. This can be done using all() :

 for line in some_file: filtered = all(i in line for i in black_list) if filtered and ':' in line: # this line is black listed -> do something else: # this line is good -> do something 

The above checks to see if there are ALL black_list elements. Use any() if you want to reject the line if any of the black_list elements is present:

 for line in some_file: filetered = any(i in line for i in black_list_2) if filtered: # this line contains at least one element of the black_list else: # this line is fine 
0
source

In your code example, it looks like you are looking for an element in a file, not just a line. Despite this, you can do something similar, which illustrates the execution as with the built-in any() function:

 def check_string(text, word_list): return any(phrase in text for phrase in word_list) def check_file(filename, word_list): with open(filename) as some_file: return any(check_string(line, word_list) for line in some_file) black_list = ["ab:", "cd:", "ef:", "gh:"] print check_file('some_file.txt', black_list) 
0
source

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


All Articles