【问题标题】:'int' object is not callable :find the sum of elements of a list'int' 对象不可调用:查找列表元素的总和
【发布时间】:2020-01-29 02:46:56
【问题描述】:

我试图在单行中查找列表中元素的总和,其中元素取自用户。但是当我运行它显示的程序时,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 不可调用或不受支持的操作数类型?给minimal reproducible example。请注意,input().split() 会给你一个字符串列表
  • 请出示您的list print(l)。
  • 使用 l = [ int(x) for x in input().split()]
  • 不工作@rajenderkumar

标签: python python-3.5


【解决方案1】:
l = [ int(x) for x in l.split()]
s=sum(l)
n=len(l)
if(s%n!=0):
    print(-1)
else:
    print(s)

使用类型转换

【讨论】:

  • 我的错误是什么?
  • sum 函数应仅使用整数列表调用。您正在传递字符串文字列表。
【解决方案2】:

您能否提供引发错误的示例输入?我敢打赌该列表同时具有intstr 类型。列表中的每个元素都需要强制转换为整数,如果不能,则程序需要退出并显示该错误,或​​者只对列表中可以强制转换的元素求和。这可以通过map 函数来完成。示例:

l=list(map(int, input()))

print(l)

s=sum(l)

n=len(l)

if(s%n!=0):

    print(-1)

(Python3) 这会将列表元素映射为 int 类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 2015-01-29
    相关资源
    最近更新 更多