Richard Rublev
Richard Rublev

Reputation: 8172

List condition to get true or false in new list

I have my list:

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

I want to create a new list, with the same amount of elements with True on 'setosa' index, and False elsewhere.

I have tried like this

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

I want a list with 5 elements:

[True, True, False, False, False]

Upvotes: 2

Views: 2810

Answers (3)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24153

You could use map, which in Python 2 returns a list:

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

In Python 3 if you need a list:

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

Upvotes: 2

Liam
Liam

Reputation: 6449

you could to use the .append() function:

new_list = []

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

Upvotes: 0

Eugene Yarmash
Eugene Yarmash

Reputation: 149953

Just use a list comprehension:

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

Upvotes: 9

Related Questions