python 實現文件查找和某些項輸出
本文是基于給定一文件(students.txt),查找其中GPA分數最高的 輸出,同時輸出其對應的姓名和學分
一. 思路
首先需要打開文件,讀取文件的每一行,將姓名,學分,GPA值分別存到三個對應的列表中,對于GPA列表進行遍歷,獲取其中值最大的一項,但是需要保存最大值對應的索引,方便輸出對應的姓名和學分項
二. 代碼
版本1
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 1 12:24:18 2018
@author: Administrator
"""
def main():
file=open("students.txt",'r')
lines=file.readlines() #使用readlines()函數 讀取文件的全部內容,存成一個列表,每一項都是以換行符結尾的一個字符串,對應著文件的一行
list_name=[] #初始化一個空列表 用來存該文件的姓名 也就是第一列
list_scores=[]
list_gpa=[]
for line in lines: #開始進行處理 把第一列存到list_name 第二列存到list_scores,,,,,
elements=line.split()
list_name.append(elements[0])
list_scores.append(elements[1])
list_gpa.append(elements[2])
max_gpa=0
index=0
for i in range (len(list_gpa)): #對于列表list_gpa 遍歷該列表找其中gpa分數最高的
if max_gpa <float(list_gpa[i]):
max_gpa=float(list_gpa[i])
index=i #這一步就是記錄list_gpa中GPA最高的在列表的第幾個位置,方面輸出對應的姓名和分數
print("the person is {0} and the scores are {1} ,the gpa is {2}".format(list_name[index],list_scores[index],max_gpa))
main()
版本2
#這個是根據第二項hours和第三項points的比值,哪個值大就輸出對應的學分points和GPA值points/hours
def main():
file=open("students.txt",'r')
lines=file.readlines()
list_name=[]
list_hours=[]
list_points=[]
for line in lines:
elements=line.split()
list_name.append(elements[0])
list_hours.append(elements[1])
list_points.append(elements[2])
list_gpa=[] #這個列表用來存放hours 和points之間的比值
for i in range(len(list_name)):
a=float(list_hours[i])
b=float(list_points[i])
c=b/a
list_gpa.append(str(c)) #把原來list_hours 和list_points中對應項的比值都存到list_gpa列表中
maxgpa=0
for i in range(len(list_gpa)): #找list_gpa中值最大的那項
if maxgpa<float(list_gpa[i]):
maxgpa=float(list_gpa[i])
index=i #記錄下gpa值最大的那項對應的索引值,方便輸出其他項
print("the max GPA is {},his name is {} and the scorespoint is {}".format(maxgpa,list_name[index],list_points[index]))
main()
以上這篇python 實現查找文件并輸出滿足某一條件的數據項方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。