0

I have a list of indexes, say [3,4,7,9]. What is the fastest way to create a binary array (in this case [0,0,0,1,1,0,0,1,0,1]). Thanks!

1
  • Each decimal digit corresponds to an index of 1 in a binary array. I can do this using "for" loop but there must be a faster approach. Commented Jul 20, 2021 at 19:03

3 Answers 3

3

With numpy:

l = [3,4,7,9]
m = np.zeros(max(l)+1)
m[l] = 1
>>> m
array([0., 0., 0., 1., 1., 0., 0., 1., 0., 1.])
Sign up to request clarification or add additional context in comments.

Comments

2

Simple list comprehension will do it:

indices = {3, 4, 7, 9}
[i in indices for i in range(10)]

Comments

2

Using a comprehension:

indices = {3,4,7,9}
output = [int(i in indices) for i in range(max(indices)+1)]

2 Comments

This has poor time complexity. indices should be a set.
very nice. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.