python implements a method of finding files and outputting data items that meet certain criteria
- 2021-06-28 12:54:35
- OfStack
python implements file lookup and some item output
This article is based on a given file (students.txt) to find the output with the highest GPA score, and to output its corresponding name and credit.
1. Ideas
First, you need to open the file, read each line of the file, save the name, credit, GPA values in three corresponding lists, and then iterate through the GPA list to get the one with the largest value, but you need to save the index corresponding to the maximum value to output the corresponding name and credit items.
2. Code
Version 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() # Use readlines() function Read the entire contents of the file and save it as 1 Lists, each 1 Items end with a line break 1 String, corresponding to the file's 1 That's ok
list_name=[] # Initialization 1 Empty list Name used to save the file That is, the first 1 column
list_scores=[]
list_gpa=[]
for line in lines: # Start processing Put the 1 Store columns in list_name No. 2 Store columns in 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)): # For lists list_gpa Walk through the list to find it gpa Highest score
if max_gpa <float(list_gpa[i]):
max_gpa=float(list_gpa[i])
index=i # this 1 Step is record list_gpa in GPA Highest at the top of the list, with respect to the output of the corresponding name and score
print("the person is {0} and the scores are {1} ,the gpa is {2}".format(list_name[index],list_scores[index],max_gpa))
main()
Version 2
# This is based on the 2 term hours And 3 term points Ratio, which value is larger will output corresponding credits points and GPA value 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=[] # This list is for storage hours and points Ratio between
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)) # Put the original list_hours and list_points The ratios of corresponding items are stored in list_gpa List
maxgpa=0
for i in range(len(list_gpa)): # look for list_gpa The item with the largest median
if maxgpa<float(list_gpa[i]):
maxgpa=float(list_gpa[i])
index=i # Record gpa The index value corresponding to the item with the largest value, which makes it easy to output other items
print("the max GPA is {},his name is {} and the scorespoint is {}".format(maxgpa,list_name[index],list_points[index]))
main()