看个栗子先
mixed_list = [False, 1, 3, True, 5]
integer_sum = 0
bool_sum = 0
for item in mixed_list:
if isinstance(item, int):
integer_sum += 1
elif isinstance(item, bool):
bool_sum += 1
print(integer_sum) # 5
print(bool_sum) # 0
为什么 bool_sum = 0, 而不是bool_sum = 2?
- 看源码可知,
bool是int的子类 - 所以
True的整数值是 1, 而False的整数值是 0
class bool(int):
"""
bool(x) -> bool
Returns True when the argument x is true, False otherwise.
The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.
"""
本文通过一个具体的Python代码示例,解释了如何区分整型和布尔型变量,并分别进行计数。示例中,混合列表包含整数和布尔值,通过遍历列表并使用isinstance()函数检查每个元素的类型,分别累加整型和布尔型的数量。
566

被折叠的 条评论
为什么被折叠?



