利用哈希来有效读取文件信息

def get_info_byName(name):
    result_f = open("participant_info.txt")
    s = {}
    for each_line in result_f:
        (s['id'],s['name'],s['country'],s['average'],s['board'],s['age']) = each_line.split(';')
        if(s['name'] == name):
            result_f.close()
            return(s)
    result_f.close()
    return(s)

result_f = open("result.txt")
winner_hash = {}
results_score = []
max = 0
for each_line in result_f:
    (num,val) = each_line.split()
    winner_hash[val] = num
result_f.close()

for score in sorted(winner_hash.keys(),reverse = True):
    print(winner_hash[score] + ' is ' + score)
    results_score.append(winner_hash[score])
    
winner_info = get_info_byName(results_score[0])
print("Winner is:" + winner_info['name'])
print(winner_info)
#participant_info.txt:

101;Tony;USA;8.32;Fish;21
102;Peter;CHINA;9.32;Fish;22
103;Mary;USA;10.32;Iron;23
104;Susan;USA;11.22;Iron;24
105;Jack;UK;12.32;Iron;25
#result.txt

Tony 122
Peter 133
Mary 142
Susan 125
Jack 116
#运行结果

Mary is 142
Peter is 133
Susan is 125
Tony is 122
Jack is 116
Winner is:Mary
{'id': '103', 'name': 'Mary', 'country': 'USA', 'average': '10.32', 'board': 'Iron', 'age': '23
'}
原文地址:https://www.cnblogs.com/liuyang92/p/7376164.html