I've been trying to come up with a one line list comprehension to do the following: Given an array of integers and a single integer, call it int1, I want to create a new array of only 0's and 1's such that the new array has a 1 if there was an int1 at that position in the original array else 0.
Is there a way to have True/False be 1/0 as in C?
array1 = [1,4,2,4,5,6,4,3]
array2 = [x == 4 for x in array1 ]
=> [False, True, False, True, False, False, True, False]
Method 1: Using for loop and Python range() function Python for loop would place 0(default-value) for every element in the array between the range specified in the range() function.
A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list. Python List comprehension provides a much more short syntax for creating a new list based on the values of an existing list.
>> 8.20 seconds As we can see, the for loop is slower than the list comprehension (9.9 seconds vs. 8.2 seconds). List comprehensions are faster than for loops to create lists.
Simply convert the boolean to int
, with int
function, like this
array2 = [int(x == 4) for x in array1]
Output
[0, 1, 0, 1, 0, 0, 1, 0]
This works because, in Python, Boolean is a subclass of int
.
True
and False
already cast to int
the way you want them to. Just convert them to int
directly:
>>> [int(t) for t in (True, True, False)]
[1, 1, 0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With