Python 中 list.count(True) 的意外结果

问题描述 投票:0回答:1

使用 list.count() 方法时,我在 Python 中遇到意外行为。当计算列表中 True 的出现次数(其中 True 未显式添加或附加到列表中)时,就会出现此问题。计数似乎报告为 2,尽管 True 预计仅在列表中出现一次。

这是一个例子:

my_list = [1, 2.5, 'isa', False, True]

计算 True 的出现次数

count_of_true = my_list.count(True)

print(count_of_true) # 输出:2(意外)

在此示例中,count_of_true 意外地报告为 2,即使 True 没有多次显式添加到列表中。

我检查了代码并确认 True 没有附加或添加到其他地方的列表中。 False 计数正确报告为 1。

有没有人遇到过类似的问题,或者可以提供有关为什么 list.count(True) 在这种情况下可能表现异常的见解?

谢谢您的帮助!

python list count boolean
1个回答
0
投票

问题在于 1 == True(且 0 == False)。

要排除 True 中的 1(如果需要的话,排除 False 中的 0),可以使用

is
运算符。该运算符不比较两个操作数,而是比较它们在内存中的位置。

要解决该问题,请考虑使用更丑陋(但有效)的代码,如下所示:

my_list = [1, 2.5, 'isa', False, True]
count_of_true = sum(1 for item in my_list if item is True)  # this
print(count_of_true) # prints 1
© www.soinside.com 2019 - 2024. All rights reserved.