python - "invalid literal for int() with base 10:"这实际上是什么意思?

标签 python int

初学者在这里!我正在编写一个简单的代码来计算一个项目在列表中出现的次数(例如 count([1, 3, 1, 4, 1, 5], 1) 将返回 3) .

这是我最初拥有的:

def count(sequence, item):
    s = 0
    for i in sequence:
       if int(i) == int(item):
           s += 1
    return s

每次提交这段代码,我都会得到

"invalid literal for int() with base 10:"

我后来发现正确的代码是:

def count(sequence, item):
    s = 0
    for i in sequence:
       if **i == item**:
           s += 1
    return s

但是,我只是想知道该错误语句的含义。为什么我不能直接留在 int() 中?

最佳答案

错误是“以 10 为底的 int() 的无效文字:”。这只是意味着您传递给 int 的参数看起来不像一个数字。换句话说,它要么是空的,要么有一个数字以外的字符。

这可以在 python shell 中重现。

>>> int("x")
ValueError: invalid literal for int() with base 10: 'x'

关于python - "invalid literal for int() with base 10:"这实际上是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30903967/

相关文章:

ios - Swift:无法从字符串转换为 int(使用 slider 标签)

python - 属性错误 : 'module' object has no attribute 'face'

python - 从 Flask 路由进行 Python 异步调用

python - 在python中查找最后一次访问的文件

python - Python中的最大 float 是多少?

java - 如何在保持顺序的情况下将 int 转换为 byte

Python - 用户输入数据类型

python 2.6.7 多处理池无法关闭

java - 非法转换异常?

python - 将 int 数组转换为 chars 数组 - Python