Issue
I have a list of lists, each indicating a numeric interval:
intervals = [[1, 4],
[7, 9],
[13, 18]
]
I need to create a list of 20 elements, where each element is 0 if its index is NOT contained in any of the intervals, and 1 otherwise. So, the desired output is:
output = [0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0]
I can think of using something simple, in the lines of:
output = zeros(20)
for index, _ in enumerate(output):
for interval in intervals:
if interval[0] <= index <= interval[1]:
output[index] = 1
but is there a more efficient way?
Solution
Essentially the same as @mozway's answer, but without creating an intermediate data structure and arguably more readable:
output = np.zeros(N, dtype=int)
for start, end in intervals:
output[np.arange(start, end+1)] = 1
Answered By - Marat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.