python 實現(xiàn)查找文件并輸出滿足某一條件的數(shù)據(jù)項方法
python 實現(xiàn)文件查找和某些項輸出
本文是基于給定一文件(students.txt),查找其中GPA分?jǐn)?shù)最高的 輸出,同時輸出其對應(yīng)的姓名和學(xué)分
一. 思路
首先需要打開文件,讀取文件的每一行,將姓名,學(xué)分,GPA值分別存到三個對應(yīng)的列表中,對于GPA列表進(jìn)行遍歷,獲取其中值最大的一項,但是需要保存最大值對應(yīng)的索引,方便輸出對應(yīng)的姓名和學(xué)分項
二. 代碼
版本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()函數(shù) 讀取文件的全部內(nèi)容,存成一個列表,每一項都是以換行符結(jié)尾的一個字符串,對應(yīng)著文件的一行 list_name=[] #初始化一個空列表 用來存該文件的姓名 也就是第一列 list_scores=[] list_gpa=[] for line in lines: #開始進(jìn)行處理 把第一列存到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 遍歷該列表找其中g(shù)pa分?jǐn)?shù)最高的 if max_gpa <float(list_gpa[i]): max_gpa=float(list_gpa[i]) index=i #這一步就是記錄list_gpa中GPA最高的在列表的第幾個位置,方面輸出對應(yīng)的姓名和分?jǐn)?shù) 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
#這個是根據(jù)第二項hours和第三項points的比值,哪個值大就輸出對應(yīng)的學(xué)分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中對應(yīng)項的比值都存到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值最大的那項對應(yīng)的索引值,方便輸出其他項 print("the max GPA is {},his name is {} and the scorespoint is {}".format(maxgpa,list_name[index],list_points[index])) main()
以上這篇python 實現(xiàn)查找文件并輸出滿足某一條件的數(shù)據(jù)項方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python教程十行代碼教你語音轉(zhuǎn)文字QQ微信聊天
QQ上面發(fā)的語音消息是可以直接文字識別的,但是微信為什么沒有呢?是因為技術(shù)太難實現(xiàn)嗎?這個很簡單啊!今天給大家介紹一下語音轉(zhuǎn)文字的原理2021-09-09Python OpenCV實現(xiàn)鼠標(biāo)畫框效果
這篇文章主要為大家詳細(xì)介紹了Python OpenCV實現(xiàn)鼠標(biāo)畫框效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-08-08