Home > OS >  How to compare a value to a list of pairs in a list comprehension?
How to compare a value to a list of pairs in a list comprehension?

Time:12-19

I need to create a list that is n long where each item is a Boolean. The item will only be True when x is in the range of one or more pairs of integers. For example, my current code is as follows:

l = [True if a < x < b or c < x < d else False for x in range(n)]

My issue is that the number of pairs will vary, so only a and b might exist in one instance, but e and f could also exist in another. If I were to structure my coordinate pairs in a list of tuples like so...

coordinates = [(a,b), (c,d), ...]

...is there a way to still do this as a list comprehension? If not, what would be the most pythonic approach?

CodePudding user response:

Yes, you can use a generator expression inside any to accomplish this:

coordinates = [(2, 4), (3, 8)]
n = 5

l = [any(a < x < b for (a, b) in coordinates) for x in range(n)]

print(l)

Output:

[False, False, False, True, True]
  • Related