当条件为非布尔值时,如何在列表理解中 "else"?
How to "else" in a list comprehension when the condition is non-boolean?
给定一个列表,例如
a = ["No", 1, "No"]
我想将其转换为新列表(或者实际上只是重新分配列表),以便每个“否”都转换为 0,例如
[0,1,0]
如果我尝试以下列表理解:
[0 for i in a if i =="No"]
这显然会导致列表忽略所有不是“否”的元素
[0,0]
如果我按照给定的引导 here 尝试:
[0 if "No" else i for i in a]
这给了我:
[0, 0, 0]
我想这是因为“否”等同于 True
。
我对列表理解中 if/else 的用法有什么误解?
Make it a boolean expression by using ==
operator
>>> a = ["No", 1, "No"]
>>> [0 if i == "No" else i for i in a]
[0, 1, 0]
Or another way is
>>> [[0, i][i != "No"] for i in a]
[0, 1, 0]
This works because i != "No"
returns a boolean value which can be then interpreted as 1
for True and 0
for false. This then is used to access that particular element from the list [0, i]
给定一个列表,例如
a = ["No", 1, "No"]
我想将其转换为新列表(或者实际上只是重新分配列表),以便每个“否”都转换为 0,例如
[0,1,0]
如果我尝试以下列表理解:
[0 for i in a if i =="No"]
这显然会导致列表忽略所有不是“否”的元素
[0,0]
如果我按照给定的引导 here 尝试:
[0 if "No" else i for i in a]
这给了我:
[0, 0, 0]
我想这是因为“否”等同于 True
。
我对列表理解中 if/else 的用法有什么误解?
Make it a boolean expression by using ==
operator
>>> a = ["No", 1, "No"]
>>> [0 if i == "No" else i for i in a]
[0, 1, 0]
Or another way is
>>> [[0, i][i != "No"] for i in a]
[0, 1, 0]
This works because i != "No"
returns a boolean value which can be then interpreted as 1
for True and 0
for false. This then is used to access that particular element from the list [0, i]