python - 强制变量为整数

标签 python

errors = int(0)
for i in range(len(expectedData)):
    if data[i] != expectedData[i]:
        errors += int(binary_compare(data[i], expectedData[i]))
return errors

我有上面的代码,我试图用它来计算一些数据的一些整数(错误数)。我已经将所有我能看到的可能的东西都转换为一个整数,但是“errors += ...”这一行仍然附加了这个值,而不是添加了它。

例如,如果我的答案应该是 7,我可能会得到 500002。(5 + 0 + 0 + .. + 2)。我以前从未遇到过这个。函数 binary_compare 也返回一个整数,但我完全不知道为什么这不起作用。

最佳答案

python 不是 javascript

当您从 count = 0 开始执行 count += value 时,无法获得连接的字符串而不是数学总和。如果您尝试将字符串添加到整数,则会引发异常:

>>> x = 0
>>> x += "1"
TypeError: unsupported operand type(s) for +=: 'int' and 'str'

要比较您不知道它们是字符串还是整数的值,我会使用

str(data[i]).strip() == str(expectedData[i]).strip()

对于非整数证明的数学和,你可能想做这样的事情

try:
    value = int(expectedData[i])
except:
    value = 0
count += value

关于python - 强制变量为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3292718/

相关文章:

python - 在类之间迭代 print()

python - 当我使用 scrapy xpath 时如何使用 count()

python - 在考虑 Pandas DataFrame 中的多列的同时对组进行迭代操作

python - 如何检测 python 应用程序 (Linux) 中的用户不活动时间?

python - 在字典中连接数组

数据科学项目的 Python 文件命名约定

python - 使用 .pth 以编程方式附加到 VirtualEnv 中的 PYTHONPATH

python - Pandas :如何映射列表列中的值?

python - 获取元素通过 python 中每个索引的列表?

python - genfromtxt 返回 NaN 行