Python “以 10 为基数的 int() 的无效文字:”这实际上是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30903967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"invalid literal for int() with base 10:" What does this actually mean?
提问by Andrew
Beginner here! I am writing a simple code to count how many times an item shows up in a list (ex. count([1, 3, 1, 4, 1, 5], 1)
would return 3).
初学者在这里!我正在编写一个简单的代码来计算一个项目在列表中出现的次数(例如count([1, 3, 1, 4, 1, 5], 1)
将返回 3)。
This is what I originally had:
这是我最初拥有的:
def count(sequence, item):
s = 0
for i in sequence:
if int(i) == int(item):
s += 1
return s
Every time I submitted this code, I got
每次我提交这个代码,我得到
"invalid literal for int() with base 10:"
“以 10 为基数的 int() 的无效文字:”
I've since figured out that the correct code is:
我后来发现正确的代码是:
def count(sequence, item):
s = 0
for i in sequence:
if **i == item**:
s += 1
return s
However, I'm just curious as to what that error statement means. Why can't I just leave in int()
?
但是,我只是好奇那个错误声明是什么意思。为什么我不能直接离开int()
?
回答by recursive
The error is "invalid literal for int() with base 10:". This just means that the argument that you passed to int
doesn't look like a number. In other words it's either empty, or has a character in it other than a digit.
错误是“以 10 为基数的 int() 的无效文字:”。这只是意味着您传递给的参数int
看起来不像数字。换句话说,它要么是空的,要么是数字以外的字符。
This can be reproduced in a python shell.
这可以在 python shell 中重现。
>>> int("x")
ValueError: invalid literal for int() with base 10: 'x'
回答by udarH3
You could try something like this if letters for example, occur in your sequence:
例如,如果字母出现在您的序列中,您可以尝试这样的操作:
from __future__ import print_function
def count_(sequence, item):
s = 0
for i in sequence:
try:
if int(i) == int(item):
s = s + 1
except ValueError:
print ('Found: ',i, ', i can\'t count that, only numbers', sep='')
return s
print (count_([1,2,3,'S',4, 4, 1, 1, 'A'], 1))