Harish Guda
Harish Guda

Reputation: 33

Converting an array to 0s and 1s

Suppose I have an array A = [13, 15, 17]. I want to create a new array B such that all entries apart from its 13th, 15th and 17th entries are 0, and each of these three are 1's. How can I do this?

Upvotes: 3

Views: 92

Answers (1)

zondo
zondo

Reputation: 20336

Use a list comprehension:

B = [int(i+1 in A) for i in range(max(A))]

For each number in the range from 0 to the highest number in A, we take int(i+1 in A). i+1 in A will be a boolean value. If that number is in A, the result will be True. Otherwise it will be False. Since bool inherits from int, we can easily convert it to a normal integer with int().

Upvotes: 7

Related Questions