3

How do I compute the inverse of what is described here: Getting indices of True values in a boolean list ? That above link always comes up when I try searching for "how to obtain the true values in a boolean list from integer indices," but it gives me the indices from the true values in a boolean list, which is the inverse of what I want...

For example, from:

t = [4, 5, 7]
count = 16

I want to obtain:

[False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]

The values are all 0 indexed, as expected with Python. I'm guessing that my question is a duplicate, but it's so annoying to not be able to find what I'm looking for every time I try to remember how to do this operation, I decided to ask a new question so my Google search will hopefully bring up this post next time.

4 Answers 4

4

You can use a list comprehension. I recommend you turn t into a set for O(1) lookup:

t_set = set(t)
res = [i in t_set for i in range(count)]
Sign up to request clarification or add additional context in comments.

Comments

3

Use a list comprehension with conditions:

print([True if i in t else False for i in range(count)])

Shorter:

print([i in t else False for i in range(count)])

Comments

2

How about this:

In [6]: holderplace =[False for i in range(count)]

In [7]: for i in t:
   ...:     holderplace[i-1]=True
   ...:     

In [8]: holderplace
Out[8]: 
[False,
 False,
 False,
 True,
 True,
 False,
 True,
 False,
 False,
 False,
 False,
 False,
 False,
 False,
 False,
 False]

In [9]: 

Comments

1

You could also try using map():

list(map(lambda x: x in t, range(count)))
# [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]

It might also be worth converting t to a set, since lookup is O(1) instead of O(N).

You could also use __contains__():

list(map(t.__contains__, range(count)))

Comments

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.