初学者来了!我正在编写一个简单的代码来计算项目在列表中显示的次数(例如,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
Run Code Online (Sandbox Code Playgroud)
每次我提交这段代码,我都会
"带有基数10的int()的无效文字:"
我已经发现正确的代码是:
def count(sequence, item):
s = 0
for i in sequence:
if **i == item**:
s += 1
return s
Run Code Online (Sandbox Code Playgroud)
但是,我只是好奇这个错误陈述的含义.为什么我不能留下来int()?
rec*_*ive 10
错误是"基数为10的int()的无效文字:".这只意味着您传递给的参数int看起来不像数字.换句话说,它是空的,或者除了数字之外还有一个字符.
这可以在python shell中重现.
>>> int("x")
ValueError: invalid literal for int() with base 10: 'x'
Run Code Online (Sandbox Code Playgroud)