为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

扬帆大鱼 2022-06-14 10:05:30
我有一个问题,我需要接受用户输入,即 (Jack,10,10,9,10,10),Jack 是学生姓名,数字是考试成绩。我需要找到这些考试成绩的平均值并用学生姓名打印出来。这个问题看起来很简单,我得到一个输出错误,上面写着:>>> calcMarks()Enter marks:Jack,10,10,9,10,10Traceback (most recent call last):File "<pyshell#32>", line 1, in <module>calcMarks()File "xyz", line 12, in calcMarksavg = 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)
查看完整描述

4 回答

?
慕标5832272

TA贡献1966条经验 获得超4个赞

avg是一个数字。为了与其他字符串连接,需要先变成一个字符串str()


此外,您正在对字符串求和,在求和之前需要将其转换为数字。


def calcMarks():

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

    userInput = input('Enter marks:')

    l = userInput.split(',')

    name = l.pop(0)

    l = [int(x) for x in l]

    avg = sum(l)/len(l)

    print(name + ' ' + str(avg))


查看完整回答
反对 回复 2022-06-14
?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

您的方法的问题是,当您读取时input总是会得到一个字符串,因此您必须将标记转换为整数来计算平均值。这是我将如何做到这一点:


def calcMarks():

    # unpack the input into user and marks

    # having split the string by ','

    user, *marks = input('Enter marks:').split(',')

    # take the average of the marks cast to int 

    avg_mark = sum(map(int,marks))/(len(marks))

    # you can use f-strings to print the output

    print(f'{user} has an average of {avg_mark}')

    # print('{} has an average of {}'.format(user, avg_mark)) # for python 3.5<

calcMarks()


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

Jack has an average of 9.8


查看完整回答
反对 回复 2022-06-14
?
胡子哥哥

TA贡献1825条经验 获得超6个赞

字符串concetanation仅在需要连接变量时才有效same data type

print(name + ' ' + str(avg))



查看完整回答
反对 回复 2022-06-14
?
慕桂英546537

TA贡献1848条经验 获得超10个赞

如果您希望获得返回intorfloat值的函数的输出,您可以添加而,不是添加:+print1


def calcMarks():

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

    userInput = input('Enter marks:')

    inputs = userInput.split(',')

    name = inputs.pop(0)

    input_list = [int(i) for i in inputs]

    #print(type(list))

    #print(type(name))

    avg = sum(input_list)/(len(input_list))

    print(name + ' ',avg)

calcMarks()

输出:


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

Jack  9.8


查看完整回答
反对 回复 2022-06-14
  • 4 回答
  • 0 关注
  • 199 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号