简体   繁体   中英

How do I get this program to print out the state with the highest score and states with score > 500?

I'm so close. I'm able to print out the max score but cannot get it to print out the state name. I'm also unsure how to get it to print out the state names with scores greater than 500. Here is some sample data. It is from a text file as you see in my code below:

New_York        497 510 
Connecticut     515 515 
Massachusetts   518 523 
New_Jersey      501 514 
New_Hampshire   522 521 
D.C.            489 476 

Here is the code I have so far:

StateFile = open ('state_satscores_2004.txt', 'r')

count = 0

ScoreList = [ ]

for line in StateFile:

    # increment adds one to the count variable

    count += 1

    # strip the newline at the end of the line (and other white space from ends)

    textline = line.strip()

    # split the line on whitespace

    items = textline.split()

    # add the list of items to the ScoreList

    ScoreList.append(items)
# print the number of states with scores that were read

print('The number of SAT Scores for states is:', count)

score = []
for line in ScoreList:
    score.append(int(line[1]))

print(max(score))

print(score>500)



for line in score:
    print('The scores are', score)


# print the lines from the list

for line in ScoreList:
    print ('The scores for ', line)



StateFile.close()

The code inside your print() call in the last line, score>500 , is actually a condition that evaluates to either True or False . It's not actually an instruction to the print() function to print every element greater than 500 .

That may be confusing to hear, since max(score) does sort of behave in that way - but max(score) is another method call that actually returns a value (which is then printed).

The simplest version of what you're looking for is a for loop - iterating over ScoreList and printing out each value that is greater than 500.

Here's an example.

...
print(max(score))

for line in ScoreList:
    if line[1] > 500 or line[2] > 500: # if either score is > 500, then...
        print(line[0]) # ...print the name of the state.

You could do this in your existing for loop on ScoreList of course; you don't need to loop over it a second time, but I wanted to show this loop by itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM