如何让这个程序打印出得分最高的州和得分>500的州?

2024-09-29 17:10:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我就差一点了。我可以打印出最高分数,但无法打印出州名。我也不确定如何让它打印出得分超过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()

Tags: ofthe代码innewforcountline
1条回答
网友
1楼 · 发布于 2024-09-29 17:10:24

最后一行print()调用中的代码score>500,实际上是一个计算结果为TrueFalse条件。它实际上并不是给print()函数的指令,用于打印大于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.

当然,您可以在ScoreList上现有的for循环中这样做;你不需要第二次循环,但我想展示这个循环本身

相关问题 更多 >

    热门问题