python 实现查找文件并输出满足某一条件的数据项方法

yipeiwu_com6年前Python基础

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 实现查找文件并输出满足某一条件的数据项方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 模拟贷款卡号生成规则过程解析

前言 笔者在测试某web系统的过程中,需要用到“贷款卡号”,且此贷款卡号仅能使用一次,保存过后下一次无法再次使用相同的卡号。 遂决定依据它的生成规则,自己写一段代码来实现。 同时为了方便...

Python数组遍历的简单实现方法小结

本文实例总结了Python数组遍历的简单实现方法。分享给大家供大家参考,具体如下: >>> os.__file__.split('\\') ['E:', 'Pyt...

Python找出文件中使用率最高的汉字实例详解

本文实例讲述了Python找出文件中使用率最高的汉字的方法。分享给大家供大家参考。具体分析如下: 这是我初学Python时写的,为了简便,我并没在排序完后再去掉非中文字符,稍微会影响性能...

python贪吃蛇游戏代码

python贪吃蛇游戏代码

本文实例为大家分享了python贪吃蛇游戏的具体代码,供大家参考,具体内容如下 贪吃蛇游戏截图: 首先安装pygame,可以使用pip安装pygame: pip install py...

python3中bytes和string之间的互相转换

前言 Python 3最重要的新特性大概要算是对文本和二进制数据作了更为清晰的区分。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。Python 3不会以任意...