O'Reilly Forums: Chapter 4 - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Chapter 4 Array only getting index [0]

#1 User is offline   bruno1067 

  • New Member
  • Pip
  • Group: Members
  • Posts: 4
  • Joined: 24-June 14
  • Gender:Male

Posted 24 June 2014 - 12:44 PM

Hi,

I can't find out why, but Phyton is only finding the index[0] from my array... Here is my code:

result_f = open("results.txt")

for line in result_f:
    scores = []
    (name, score) = line.split()
    scores.append(score)

result_f.close

print(scores[0])
print(scores[1])
print(scores[2])


But Python keeps returning:

>>>
8.31
Traceback (most recent call last):
File "/Users/Bruno/Documents/Surf.py", line 12, in <module>
print(scores[1])
IndexError: list index out of range


Tried the code from the labs file, but I'm getting the same error. What's happening?
0

#2 User is offline   bruno1067 

  • New Member
  • Pip
  • Group: Members
  • Posts: 4
  • Joined: 24-June 14
  • Gender:Male

Posted 24 June 2014 - 12:59 PM

Hm... I got the scores on order by putting logic on paper... But I still want to learn what the chapter says...

result_f = open("results.txt")

highest_score = 0
second_high = 0
third_high = 0

for line in result_f:
    (name, score) = line.split()
    
    if float(score) > float(highest_score):
        third_high = second_high
        second_high = highest_score
        highest_score = score

result_f.close


print("The Results are: ")
print(highest_score, second_high, third_high)

0

#3 User is offline   bruno1067 

  • New Member
  • Pip
  • Group: Members
  • Posts: 4
  • Joined: 24-June 14
  • Gender:Male

Posted 25 June 2014 - 02:31 AM

I GOT IT!!!

I just had to put the array/list outside the loop, because everytime the loop iterated, it cleaned my array when it got to the line
scores = []
. And then, every new score was being assigned to index
[0]
again. :D

Phew...
0

#4 User is offline   bruno1067 

  • New Member
  • Pip
  • Group: Members
  • Posts: 4
  • Joined: 24-June 14
  • Gender:Male

Posted 25 June 2014 - 02:37 AM

And by the way, my logic above is wrong
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users