Skip to content Skip to sidebar Skip to footer

Unable To Exclude Items From A List, In A While Loop, That Are In A Certain Range

So I posted a question before, but it was too simplified and rightly got flagged as a duplicate. I'm now posting my problem in more detail so my issue might, hopefully, be resolved

Solution 1:

With vanilla python, you can generalise using any/all. I'm going with any here.

>>> [x for x in b if not any(i <= x <= j for i, j in zip(a[::2], a[1::2]))]
[1.0, 100.0]

This zips every alternate pair of list items with zip, and one by one check to ensure that x is not in any of them.

If you're interested in a performance, consider a pandas approach. You can build an Intervalindex, right for the task. Searching is logarithmic, and very fast.

>>> import pandas as pd
>>> idx = pd.IntervalIndex.from_arrays(a[::2], a[1::2], closed='both')
>>> [x for x, y in zip(b, idx.get_indexer(b)) if y == -1]
[1.0, 100.0]

Post a Comment for "Unable To Exclude Items From A List, In A While Loop, That Are In A Certain Range"