【发布时间】:2019-02-24 13:21:11
【问题描述】:
在我的 python 代码中,我将一些 bool() 转换为我知道可能已经是布尔值的变量。这有什么缺点吗? (性能等)
这是我正在使用的函数的基本克隆。
import re
pattern= "[A-Z]\w[\s]+:"
other_cond= "needs_to_be_in_the_text"
def my_func(to_check: str) -> bool:
res = re.search(pattern, to_check)
res2 = other_cond in to_check
return bool(res), bool(res2) # res2 either None or True
# I need boolean returns because later in my code I add all these
# returned values to a list and use min(my_list) on it. to see if
# there's any false value in there. min() on list with None values causes exception
【问题讨论】:
-
你的问题太笼统了,你能提供一个示例代码吗?一般来说,显式转换为
bool看起来很吵,并且会损害可读性 -
不需要做就不要做。
-
@AzatIbrakov 我添加了我的函数的示例版本。
-
您的意思是“真实”吗?
re.search的结果肯定不是布尔值。 -
@tobias_k Ups ye 我忘了添加另一部分,我在函数中检查了多个内容,所有返回的内容都进入一个列表,该列表稍后使用 min() 和 None 值导致那里出现异常。