LucaS
LucaS

Reputation: 153

Python: Find index by range in multidimensional list

I'm newbie in python. I have this list for example:

[[1, 10],[11, 20],[21,30]]

Then I have a number 17. How can I find index by range. Number 17 is between 11 and 20. Index will be 1. I can do it with loop. Is there a way without loop by built in function?

Upvotes: 1

Views: 150

Answers (3)

user459872
user459872

Reputation: 24562

You could use generator expression.

>>> def find_index_by_range(*, collection, target):
...     return next(
...         (index for index, value in enumerate(collection) if target in range(*value)),
...         None,
...     )
...

>>> ranges = [[1, 10],[11, 20],[21,30]]
>>> find_index_by_range(collection=ranges, target=17)
1
>>> find_index_by_range(collection=ranges, target=28)
2

Upvotes: 1

Shubham
Shubham

Reputation: 1438

This seems like the simplest way to do what you need to:

ranges = [[1, 10],[11, 20],[21,30]]
n = 17
for i, r in enumerate(ranges):
    if n in range(r[0], r[1]+1):
        print(i)
        break

Btw, for the kind of ranges you have, you can go for a more mathematical approach:

index = (n-1) // 10

Upvotes: 2

Mario Ishac
Mario Ishac

Reputation: 5877

You can use filter combined with next:

ranges = [[1, 10],[11, 20],[21,30]]
target = 17

target_range = next(filter(lambda range: range[0] < target < range[1], ranges))

target_range will be [11, 20] in this case.

filter here is responsible for excluding ranges that do not have target within them. And assuming that the ranges do not overlap, filter will exclude every range but one, and we can get that one with next.

You can also change up the criteria for what ranges are kept. If you consider 11 part of [11, 20] (right on the border), you can do range[0] <= target <= range[1] instead.

Upvotes: 1

Related Questions