有一个文件以相同的顺序包含以下信息:LastName FirstName IDnumber score1 score2 finalScore。我的目标是确定整个文件的最低finalScore以及获得该分数的学生的ID号。这就是我所拥有的,但我不确定如何将IDnumber与得分相关联。
scores = open('text.txt', 'w')
scores.write('Johnson Jeff 1213 91 92 94\n')
scores.write('Johnson Alan 5553 81 82 84\n')
scores.write('Johnson Bart 8973 91 82 98\n')
scores.close()
grades = open('text.txt','r')
listy = []
for i in grades:
a = i.split()
for j in a[3:]:
listy.append(j)
print(min(listy))
答案 0 :(得分:7)
使用字典会很容易。但是,如果您希望按照现在的方式执行此操作,则可以将min(..)
与自定义密钥一起使用。
>>> s = ['Johnson Jeff 1213 91 92 94', 'Johnson Alan 5553 81 82 84', 'Johnson Bart 8973 91 82 98']
>>> min(s, key=lambda x: int(x.split()[5]))
'Johnson Alan 5553 81 82 84'
答案 1 :(得分:2)
由于我觉得你是Python的初学者,我编写的代码尽可能简单
算法:
以下是代码:
#Your Code:
scores = open('text.txt', 'w')
scores.write('Johnson Jeff 1213 91 92 94\n')
scores.write('Johnson Alan 5553 81 82 84\n')
scores.write('Johnson Bart 8973 91 82 98\n')
scores.close()
grades = open('text.txt','r'
#Added code
IDS={}
for line in grades:
line_items = line.split()
if line_items[5] in IDS:
IDS[line_items[5]].append(line_items[2])
else:
IDS[line_items[5]] = [line_items[2]]
scores = IDS.keys()
scores = list(scores)
scores.sort(key = int)
print("The id of the lowest FinalScore is",IDS[scores[0]])
希望这会有所帮助:)
答案 2 :(得分:0)
不是创建列表而是创建一个字典和ID号作为键和分数列表作为值:
grades = open('text.txt','r')
dd={}
for i in grades:
dd[i.split()[2]]=min(i.split()[3:])
min_score = min(dd, key=dd.get)
min_score是你的答案
答案 3 :(得分:0)
你问过如何将文件读取到dict,这里有一些代码:
d = dict()
with open('text.txt','r') as f:
for line in f.readlines():
data = line.split(" ")
d[data[2]] == {
"lastName":data[0],
"firstName":data[1],
"score1":data[3],
"score2":data[4],
"finalScore":data[5]}
这会将您的文件写入字典d
,然后使用密钥使用min()
进行迭代:
lowestScore = min(d, key = lambda k: d[k]['finalScore'])
#this returns the key in d with the lowest finalScore
答案 4 :(得分:0)
转换为dict仅适用于小文件。
# pseudocode for huge files
with open(filename) as f:
result_lines = [] # if many people has same score
min_score = 100500
for line in f:
score = get_score(line) # get_score should return int
if score < min_score:
result_line = [line]
elif score == min_score:
result_line.append(line)