我就差一点了。我可以打印出最高分数,但无法打印出州名。我也不确定如何让它打印出得分超过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()
最后一行
print()
调用中的代码score>500
,实际上是一个计算结果为True
或False
的条件。它实际上并不是给print()
函数的指令,用于打印大于500
的每个元素这听起来可能会让人困惑,因为
max(score)
确实有这样的行为——但是max(score)
是另一个方法调用,它实际返回一个值(然后打印)最简单的版本是for循环,它遍历
ScoreList
并打印出每个大于500的值下面是一个例子
当然,您可以在
ScoreList
上现有的for循环中这样做;你不需要第二次循环,但我想展示这个循环本身相关问题 更多 >
编程相关推荐