初学者在这里!我正在编写一个简单的代码来计算一个项目在列表中出现的次数(例如 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/