Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python +;的操作数类型不受支持:';int';和';str';——尝试对一行中的所有整数求和_Python_Python 3.x - Fatal编程技术网

Python +;的操作数类型不受支持:';int';和';str';——尝试对一行中的所有整数求和

Python +;的操作数类型不受支持:';int';和';str';——尝试对一行中的所有整数求和,python,python-3.x,Python,Python 3.x,我很难输出我给代码的任何一组整数的和,因为我试图用它来实现通用性,但是我得到的只是一个操作数错误,在这个例子中我应该得到7 我的代码 sum1 = input('Enter a set of integers: ') sum2 = sum(sum1) print('The sum of the integers entered are: ' , sum2) line 2, in <module> sum2 = sum(sum1) TypeError: unsupported

我很难输出我给代码的任何一组整数的和,因为我试图用它来实现通用性,但是我得到的只是一个操作数错误,在这个例子中我应该得到7

我的代码

 sum1 = input('Enter a set of integers: ')
 sum2 = sum(sum1)
 print('The sum of the integers entered are: ' , sum2)

line 2, in <module>
sum2 = sum(sum1)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
sum1=input('输入一组整数:')
sum2=总和(sum1)
print('输入的整数之和为:',sum2)
第2行,在
sum2=总和(sum1)
TypeError:不支持+:“int”和“str”的操作数类型

当我输入时,我的输出应该是7:5,2,但是我得到了错误消息,我如何修复它

您正在尝试获取字符串的总和
'5,2'
。这行不通。首先需要执行两个步骤:

  • 拆分字符串,以便您有一个要求和的事物列表(使用
    Split
    )。现在不再使用
    '5,2'
    ,而是使用
    ['5','2']
  • 将字符串转换为数字(使用
    int
    map
    将其转换为所有片段)。现在,您将拥有
    [5,2]
    ,而不是
    [5,2]
  • 这样把它们放在一起:

    sum2 = sum(map(int, sum1.split(',')))
    

    在Python3.x中,通过
    input
    接收的值存储为字符串。因此,如果您输入
    5,2
    ,您实际上将拥有
    sum1=“5,2”
    。在求和之前,您必须首先解析该数据以获得字符串列表。通过一些快速的google搜索,您将发现如何将逗号分隔的字符串转换为字符串列表,以及如何将列表中的每个成员转换为整数。提示:您可以使用
    str.split
    方法和
    map(int,list)
    。就在那时,在所有这些之后,您将能够
    sum()
    考虑通常的责难:回答明显重复的问题(参考第3个要点的“回答好问题”部分)。也就是说,这是一个比链接副本更好的答案——也许把它移到那里?