求和函数概率类型错误:+ 不支持的操作数类型:“int"和“str"

Sum function prob TypeError: unsupported operand type(s) for +: #39;int#39; and #39;str#39;(求和函数概率类型错误:+ 不支持的操作数类型:“int和“str)
本文介绍了求和函数概率类型错误:+ 不支持的操作数类型:“int"和“str"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我是 python (PYTHON 3.4.2) 的新手,我正在尝试制作一个程序来添加和除以查找用户输入的平均值或平均值,但我不知道如何添加我收到的号码.

I'm new to python (PYTHON 3.4.2) and I'm trying to make a program that adds and divides to find the average or the mean of a user's input, but I can't figure out how to add the numbers I receive.

当我在命令提示符下打开程序时,它会接受我输入的数字,并且如果我使用打印功能也会打印它,但它不会将数字相加.

When I open the program at the command prompt it accepts the numbers I input and would print it also if I use a print function, but it will not sum the numbers up.

我收到此错误:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

我的代码如下:

#Take the user's input
numbers = input("Enter your numbers followed by commas: ")
sum([numbers])

任何帮助将不胜感激.

推荐答案

input 将输入作为字符串

>>> numbers = input("Enter your numbers followed by commas: ")
Enter your numbers followed by commas: 1,2,5,8
>>> sum(map(int,numbers.split(',')))
16

你告诉用户输入用逗号分隔,所以你需要用逗号分割字符串,然后将它们转换为 int 然后求和

you are telling user to give input saperated by comma, so you need to split the string with comma, then convert them to int then sum it

演示:

>>> numbers = input("Enter your numbers followed by commas: ")
Enter your numbers followed by commas: 1,3,5,6
>>> numbers
'1,3,5,6'   # you can see its string
# you need to split it
>>> numbers = numbers.split(',')
>>> numbers
['1', '3', '5', '6']
# now you need to convert each element to integer
>>> numbers = [ x for x in map(int,numbers) ]
or
# if you are confused with map function use this:
>>> numbers  = [ int(x) for x in numbers ]
>>> numbers
[1, 3, 5, 6]
#now you can use sum function
>>>sum(numbers)
15

这篇关于求和函数概率类型错误:+ 不支持的操作数类型:“int"和“str"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)