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

