首页 > 解决方案 > 如何让这个程序打印出得分最高的州和得分 > 500 的州?

问题描述

我是如此接近。我可以打印出最高分数,但无法打印出州名。我也不确定如何让它打印出分数大于 500 的州名。这是一些示例数据。它来自一个文本文件,如下面的代码所示:

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

这是我到目前为止的代码:

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()

标签: python

解决方案


print()最后一行调用中的代码score>500, 实际上是一个计算结果为or的条件。它实际上并不是对函数的指令来打印每个大于.TrueFalseprint()500

听到这可能会令人困惑,因为max(score)确实以这种方式表现 - 但max(score)实际上是另一种方法调用,它实际上返回一个值(然后打印)。

您正在寻找的最简单版本是 for 循环 - 迭代ScoreList并打印出每个大于 500 的值。

这是一个例子。

...
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.

当然,您可以在现有的 for 循环中执行此操作ScoreList;你不需要第二次循环它,但我想单独展示这个循环。


推荐阅读