List condition to get true or false on a new list

I have a list:

>>> labels = ['setosa', 'setosa', 'versicolor', 'versicolor', 'virginica']

      

I want to create a new list with the same number of elements from True

to 'setosa'

index and False

elsewhere.

I tried like this

>>> b = 'setosa' in labels
>>> b
True

      

I need a list of 5 elements:

[True, True, False, False, False]

      

+3


source to share


3 answers


Just use a list comprehension:



lst = [label == "setosa" for label in labels]

      

+9


source


You can use , which in Python 2 returns : map

list

>>> labels = ['setosa', 'setosa', 'versicolor', 'versicolor', 'virginica']
>>> map('setosa'.__eq__, labels)
[True, True, False, False, False]

      



In Python 3, if you want a list:

>>> list(map('setosa'.__eq__, labels))
[True, True, False, False, False]

      

+2


source


you can use the function .append()

:

new_list = []

for element in labels: new_list.append('setosa' == element)

      

0


source







All Articles