Another loop iteration of list

58 Views Asked by At

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
4

There are 4 best solutions below

0
On BEST ANSWER

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]))
0
On

The line line=highScore.readline().strip('\n') is probably not what your trying to do. I think you want to read the entire file and break by new lines. So replace readline with read.

lines = highScore.read().strip('\n')

Then instead of a while loop you can use a for loop

for line in lines:
    for items in line.split(', '):
         score.append(list(items[0], items[1:]))
1
On

i think z is a 2D array so replace this line :

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

with this :

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

Just use str.format and access the subelements by index:

In [10]: z = [[1,2],[3,4]]


In [11]: for i in z:
   ....:     print("{}        {}".format(i[0],i[1]))
   ....:     
1       2
3       4

You are iterating over the element in z so just access each subelement by the index.