Search code examples
pythonfor-loopwhile-looppython-3.1

Another loop iteration of list


How to write this code correctly?

highScore=open('scores.txt',mode='r')
score=[]
i=0
print("\nName\t\tScore")
line=highScore.readline().strip('\n')
while line!="":
    line=str(line).split(', ')
    x=[line[0],int(line[1])]
    score.append(x)
    line=highScore.readline()
z=sorted(score, key=itemgetter(1), reverse=False)
for i in z:
    print(str(z[i][0])+"\t\t"+str(z[i][1]))
    i+=1

Expected to show name with tab with score of the same entry.

But error shown :

TypeError: list indices must be integers, not list

Solution

  • Because i is not the index, it is each element out of your list. See the below example

    z = 'abcde'
    for i in z:
        print i
    
    a
    b
    c
    d
    e
    

    So you would want to change your code to

    for i in z:
        print(str(i[0])+"\t\t"+str(i[1]))