为什么我在尝试将记录中的项设为整数时会出错?

2024-10-01 13:26:05 发布

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

我的代码有点问题。这段代码的目的是让用户的分数与他们的名字在一个元组中配对,然后按字母顺序、数字顺序对这些分数排序,最后求平均值。我在完成这个项目的边缘,但这个错误继续阻碍我,所以我希望获得编程社区的帮助。你知道吗

if Class == 'Year5S':
    Year5S = open ('Year5S.txt', 'r')
    Year5S = Year5S.read()
    print ('\nThe others in your class have scored the following:\n' + Year5S + '\n')

    Year5Sa = open ('Year5S.txt', 'a')
    Year5Sa.write (Name)
    Year5Sa.write (",")
    Year5Sa.write (str(Score))
    Year5Sa.write (",")
    Year5Sa.close()
    print("Would you like to see the scores sorted Alphabetically, Numerically or Averaged?")
    order=input()

i=0
record={}

itemsS = Year5S.split(",")
length = len(itemsS)
length = length-1
average_dict={}
average = {}



for i in range(0,length,2): #We are incrementing by 2 because we want to jump to every other item in the list (names of teams)
        Firstname = itemsS[i]
        score = itemsS[i+1]
        record[Firstname]=score
        if Firstname not in average_dict:
            average_dict[Firstname] = []
            average_dict[Firstname].append(score)
        if len(average_dict[Firstname]) >3:
            average_dict[Firstname].pop(0)
        if Firstname not in average:
            collection = sum(average_dict[Firstname])/len(average_dict[Firstname])
            collection = round(collection)
            average[Firstname] = collection

sorted_average = sorted(average.items(), key=lambda x: x[1], reverse = True)



sorted_Alist=sorted(record.items(), key=lambda x: x[0])



sorted_Nlist=sorted(record.items(), key=lambda x: x[1])



if order == "Alphabetically":
        print(sorted_Alist)

elif order == "Numerically":
        print(sorted_Nlist)

elif order == "Averaged":
        print(sorted_average)

我继续得到这个错误。你知道吗

 Traceback (most recent call last):
  File "C:\Users\user\Downloads\Arithmetic Game Experimental.py", line 125, in <module>
    collection = sum(average_dict[Firstname])/len(average_dict[Firstname])
TypeError: unsupported operand type(s) for +: 'int' and 'str'

我试图使记录为整数,但这是一个失败的尝试,我得到了这个错误。typeerror: int() argument must be a string or a number, not 'list'

如何将记录设为整数,以便将整数内的分数相加,然后除以整数内的分数得到平均值?提前谢谢。你知道吗

这些是文本文件的内容。 Olachi Akin, 5, Olachi Akin, 5, Olachi Akin 7,Olachi Akin,1,Olachi Akin,1,Olachi Akin,0,Olachi Akin,0,Olachi Akin,0,Olachi Akin,0,Olachi Akin,0,Olachi Akin,1,Olachi Akin,2,Olachi Akin,0,Olachi Akin,0,Olachi Akin,0,Olachi Akin,1,Olachi Akin,0,Olachi Akin,0,Olachi Akin,0,Olachi Akin,1,Olachi Akin,0,Olachi Akin,0,Olachi Akin,0,Olachi Akin,0,


Tags: iniforderfirstname分数dictcollectionwrite