当我尝试在记录整数中创建项目时,为什么会出现错误?

时间:2015-04-13 20:37:45

标签: python list math python-3.x record

我的代码在这里有点问题。此代码的目的是让用户获得'得分与元组中的名称配对,然后按字母顺序,数字顺序对这些得分进行排序,并最终进行平均。我即将完成这个项目,但这个错误继续阻碍我,所以我希望得到编程社区的帮助。

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,

1 个答案:

答案 0 :(得分:0)

替换

score = itemsS[i+1]  

通过

score = int(itemsS[i+1])