Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list comprehensions: set all elements in an array to 0 or 1

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]
like image 679
MarkAWard Avatar asked Feb 22 '14 04:02

MarkAWard


People also ask

How do you assign a zero to all elements of an array in Python?

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.

How do list comprehensions work in Python?

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.

How much faster are list comprehensions than for loops?

>> 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.


2 Answers

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.

like image 53
thefourtheye Avatar answered Nov 04 '22 00:11

thefourtheye


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]
like image 37
Free Monica Cellio Avatar answered Nov 03 '22 22:11

Free Monica Cellio