I want to filter a list of strings that includes any specific string with using list comprehension. I tried following the code, but it didn't work.
ignore_paths = ['.ipynb_checkpoints', 'New', '_calibration', 'images']
A = [x for x in lof1 if ignore_paths not in x]
but when I try with one string, it will work:
A = [x for x in lof1 if 'images' not in x]
in fact, I want to define a list of a forbidden path (or string) and check if there is a certain path that exists, then ignore that.
I can do that with normal for and if loop and check one by one, but it is not fast. I am looking for a fast way because I need to check around 150k paths.
Thanks
EDIT: To make it clear, if I had a list of files as below:
lof1 = ['User/images/20210701_151111_G1100_E53100_r121_g64_b154_WBA0_GA0_EA0_6aa87af_crop.png', 'User/images/16f48a97-7111-4f66-92cc-dc7329e7ec92.png', 'User/images/image_2022_06_21-11_41_04_AM.png']
I need to return an empty list since all of the elements contain 'images'
CodePudding user response:
Do you have duplicates? if not, you can use sets which will be very fast
allowed = set(lof1) - set(ignore_paths)
CodePudding user response:
Try:
A = [x for x in lof1 if x not in ignore_paths]