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

2024-10-04 11:27:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,我需要采取用户输入即(杰克,10,10,9,10,10)与杰克是学生的名字和数字是考试成绩。我需要找到这些考试成绩的平均值,并打印出学生的名字。这个问题看起来很简单,我得到一个输出错误,它说:

>>> 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)

Tags: nameintypeline名字学生listfile
3条回答

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))
def calcMarks():
    #input = Jack,10,10,9,10,10
    userInput = input('Enter marks:')
    l = userInput.split(',')[1:]
    #print(type(list))
    #print(type(name))
    return sum(map(int, l))/(len(l))

这种方法的问题是,当从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

相关问题 更多 >