How "more" in the list comprehension when the condition is not logical?

Given a list for example

a = ["No", 1, "No"]

I want to convert this to a new list (or just just rewrite the list) so that every No converts to 0, for example.

[0,1,0]

If I try to understand the following:

[0 for i in a if i =="No"]

This obviously leads to a list that omits every item that is not "No"

[0,0]

If I follow the example here and try:

[0 if "No" else i for i in a]

This gives me:

[0, 0, 0]

And I think this is because “No” matches True.

What I don't understand about using if / else in list comprehension?

+4
source share
1 answer

Make this a logical expression using the operator ==

>>> a = ["No", 1, "No"]
>>> [0 if i == "No" else i for i in a]
[0, 1, 0]

Or another way

>>> [[0, i][i != "No"] for i in a]
[0, 1, 0]

, i != "No" , 1 True 0 false. [0, i]

+4

All Articles