简体   繁体   中英

How to find out if a number is in a list of ranges?

Okay so say I have a list of ranges like

a = [[167772352, 167772415], [167772160, 167772223], [167772288, 167772351], [167772224, 167772255]]

and then I have a number like

b = 167772241

Now I know that b is within the 4th item of the list but how would I check that b is within that in a optimal way? I've thought of using a for loop going through each number of the list and then inserting when the loop breaks but I feel like there has to be some python library function that could handle this? Any suggestion would be welcome!

Simply iterate over the list, take both values and create a range from those values and check if b in range(...) , also use enumerate , start it from 1 and you will get in which consecutive range in the list the number is.

a = [[167772352, 167772415], [167772160, 167772223], [167772288, 167772351], [167772224, 167772255]]
b = 167772241

for index, (start, end) in enumerate(a, start=1):
    if b in range(start, end + 1):
        print(index)
        break

You can also use a list comprehension:

a = [[167772352, 167772415], [167772160, 167772223], [167772288, 167772351], [167772224, 167772255]]
b = 167772241

index = [b in range(start, end + 1) for start, end in a].index(True) + 1
print(index)

Also note the end + 1 used in both range s, that is because the range doesn't include its end value so adding 1 means that the range is inclusive on both sides. Also both methods will get the index that starts from one, which is how you would usually count (1, 2, 3, 4, ...) as you have stated in your question that b should be in the fourth range (which means that you started counting from 1)

You could use map in the following way:

a = [[167772352, 167772415], [167772160, 167772223], [167772288, 167772351], [167772224, 167772255]]
b = 167772241
c = list(map(lambda a_: b in range(a_[0], a_[1] + 1), a))

The output will be a list of booleans that will indicate whether b is contained in each of a's ranges:

out: [False, False, False, True]

map takes two arguments. The first is a function (or a lambda), that it will then apply to each element of the list that you pass as a second parameter. map returns an special object, but you can easily convert it into a list by using list() .

You could write a regular function that will check if b is in range, but using a lambda allows you to write the expression in one line. It takes one argument, a_ , which will be populated with each element of the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM