This question already has an answer here:
Given a list e.g.
a = ["No", 1, "No"]
I want to convert this to a new list (or actually just re-assign the list) such that each "No" gets converted to a 0 e.g.
[0,1,0]
If I try the following list comprehension:
[0 for i in a if i =="No"]
This obviously results in a list that omits every element that is not "No"
[0,0]
If I follow the lead given here and try:
[0 if "No" else i for i in a]
This gives me:
[0, 0, 0]
And I guess this is because "No" equates to True
.
What am I misunderstanding about the usage of if/else in a list comprehension?
Aucun commentaire:
Enregistrer un commentaire