'int' 对象不可调用:查找列表元素的总和
'int' object is not callable :find the sum of elements of a list
我试图在一行中查找列表中元素的总和,其中元素取自用户。但是当我 运行 它显示的程序时,int
对象不可调用。
我的代码:
l=input().split()
print(l)
s=sum(l)
n=len(l)
if(s%n!=0):
print(-1)
当我 运行 我的程序:
*error in line3*
TypeError: unsupported operand type(s) for +: 'int' and 'str'
和
'int' object is not callable
您能否提供引发错误的示例输入?我敢打赌该列表同时具有 int
和 str
类型。列表中的每个元素都需要被强制转换为整数,如果不能,则程序需要退出并出现该错误,或者只对列表中可以强制转换的元素求和。这可以通过 map
函数来完成。示例:
l=list(map(int, input()))
print(l)
s=sum(l)
n=len(l)
if(s%n!=0):
print(-1)
(Python3)
这会将列表元素映射到类型 int。
l = [ int(x) for x in l.split()]
s=sum(l)
n=len(l)
if(s%n!=0):
print(-1)
else:
print(s)
使用类型转换
我试图在一行中查找列表中元素的总和,其中元素取自用户。但是当我 运行 它显示的程序时,int
对象不可调用。
我的代码:
l=input().split()
print(l)
s=sum(l)
n=len(l)
if(s%n!=0):
print(-1)
当我 运行 我的程序:
*error in line3*
TypeError: unsupported operand type(s) for +: 'int' and 'str'
和
'int' object is not callable
您能否提供引发错误的示例输入?我敢打赌该列表同时具有 int
和 str
类型。列表中的每个元素都需要被强制转换为整数,如果不能,则程序需要退出并出现该错误,或者只对列表中可以强制转换的元素求和。这可以通过 map
函数来完成。示例:
l=list(map(int, input()))
print(l)
s=sum(l)
n=len(l)
if(s%n!=0):
print(-1)
(Python3) 这会将列表元素映射到类型 int。
l = [ int(x) for x in l.split()]
s=sum(l)
n=len(l)
if(s%n!=0):
print(-1)
else:
print(s)
使用类型转换