列表python的总和+从列表中删除字符串

我有一个问题,我需要接受用户输入,即 (Jack,10,10,9,10,10),Jack 是学生姓名,数字是考试成绩。我需要找到这些考试成绩的平均值并用学生姓名打印出来。这个问题看起来很简单,我得到一个输出错误,上面写着:


>>> calcMarks()

Enter marks:Jack,10,10,9,10,10

Traceback (most recent call last):

File "<pyshell#32>", line 1, in <module>

calcMarks()

File "xyz", line 12, in calcMarks

avg = sum(list[0:len(list)])

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

>>> 

到目前为止,这是我的代码:


def calcMarks():

    #input = Jack,10,10,9,10,10

    userInput = input('Enter marks:')

    list = userInput.split(',')

    name = list.pop(0)

    #print(type(list))

    #print(type(name))

    avg = sum(list)/(len(list)-1)

    print(name + ' ' + avg)


扬帆大鱼
浏览 200回答 4
4回答

慕标5832272

avg是一个数字。为了与其他字符串连接,需要先变成一个字符串str()此外,您正在对字符串求和,在求和之前需要将其转换为数字。def calcMarks():&nbsp; &nbsp; #input = Jack,10,10,9,10,10&nbsp; &nbsp; userInput = input('Enter marks:')&nbsp; &nbsp; l = userInput.split(',')&nbsp; &nbsp; name = l.pop(0)&nbsp; &nbsp; l = [int(x) for x in l]&nbsp; &nbsp; avg = sum(l)/len(l)&nbsp; &nbsp; print(name + ' ' + str(avg))

沧海一幻觉

您的方法的问题是,当您读取时input总是会得到一个字符串,因此您必须将标记转换为整数来计算平均值。这是我将如何做到这一点:def calcMarks():&nbsp; &nbsp; # unpack the input into user and marks&nbsp; &nbsp; # having split the string by ','&nbsp; &nbsp; user, *marks = input('Enter marks:').split(',')&nbsp; &nbsp; # take the average of the marks cast to int&nbsp;&nbsp; &nbsp; avg_mark = sum(map(int,marks))/(len(marks))&nbsp; &nbsp; # you can use f-strings to print the output&nbsp; &nbsp; print(f'{user} has an average of {avg_mark}')&nbsp; &nbsp; # print('{} has an average of {}'.format(user, avg_mark)) # for python 3.5<calcMarks()Enter marks:Jack,10,10,9,10,10Jack has an average of 9.8

胡子哥哥

字符串concetanation仅在需要连接变量时才有效same data type。print(name&nbsp;+&nbsp;'&nbsp;'&nbsp;+&nbsp;str(avg))

慕桂英546537

如果您希望获得返回intorfloat值的函数的输出,您可以添加而,不是添加:+print1def calcMarks():&nbsp; &nbsp; #input = Jack,10,10,9,10,10&nbsp; &nbsp; userInput = input('Enter marks:')&nbsp; &nbsp; inputs = userInput.split(',')&nbsp; &nbsp; name = inputs.pop(0)&nbsp; &nbsp; input_list = [int(i) for i in inputs]&nbsp; &nbsp; #print(type(list))&nbsp; &nbsp; #print(type(name))&nbsp; &nbsp; avg = sum(input_list)/(len(input_list))&nbsp; &nbsp; print(name + ' ',avg)calcMarks()输出:Enter marks:Jack,10,10,9,10,10Jack&nbsp; 9.8
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python