Python small project (student achievement management system) 7. Sorting and display

Python small project (student achievement management system)

Day 7: sorting and displaying

1, sort() section

For the sorting part, the first thing to do is to judge whether there is a. txt file, and use the readlines method to read the information in the. txt file.

def sort():
    if os.path.exists(filename):   #Determine whether a. txt file exists
        with open(filename,'r',encoding='UTF-8') as file:
            student_old= file.readlines()     #Put the contents of the file into the student_old
            #print('output student_old')
            #print(student_old)
        student_new = []
        for item in student_old:
            d = dict(eval(item))
            #print('output d ')
            #print(d)
            student_new.append(d)
            #print('output student_new')
            #print(student_new)
    else:
        return

=========================================================================

If you don't know student here_ old,d,student_ What data does new have? You can run the code above # inside.

  First, the student.txt file contains the information of four students: 1, 2, 3 and 4. Then we run through the code and look at the output.

Here we can find that because readlines reads all the information in the. txt file at once, student_ There are four pieces of student information in old. And this is a list.

student_old =

["{'name': '1', 'id': '1', 'chinese': '1', 'math': '1', 'english': '1'}\n",

"{'name': '2', 'id': '2', 'chinese': 2, 'math': 2, 'english': 2}\n",

"{'name': '3', 'id': '3', 'chinese': 3, 'math': 3, 'english': 3}\n",

"{'name': '4', 'id': '4', 'chinese': 4, 'math': 4, 'english': 4}\n"]

Next, start traversing the student_old, take out the first one, change it into a dictionary, give it to d, and then add it to new:

First traversal

Output d
{'name': '1', 'id': '1', 'chinese': '1', 'math': '1', 'english': '1'}
Output student_new
[{'name': '1', 'id': '1', 'chinese': '1', 'math': '1', 'english': '1'}]

Second traversal

Output d
{'name': '2', 'id': '2', 'chinese': 2, 'math': 2, 'english': 2}
Output student_new
[{'name': '1', 'id': '1', 'chinese': '1', 'math': '1', 'english': '1'}, {'name': '2', 'id': '2', 'chinese': 2, 'math': 2, 'english': 2}]

Third traversal

Output d
{'name': '3', 'id': '3', 'chinese': 3, 'math': 3, 'english': 3}
Output student_new
[{'name': '1', 'id': '1', 'chinese': '1', 'math': '1', 'english': '1'}, {'name': '2', 'id': '2', 'chinese': 2, 'math': 2, 'english': 2}, {'name': '3', 'id': '3', 'chinese': 3, 'math': 3, 'english': 3}]
 

Fourth traversal

Output d
{'name': '4', 'id': '4', 'chinese': 4, 'math': 4, 'english': 4}
Output student_new
[{'name': '1', 'id': '1', 'chinese': '1', 'math': '1', 'english': '1'}, {'name': '2', 'id': '2', 'chinese': 2, 'math': 2, 'english': 2}, {'name': '3', 'id': '3', 'chinese': 3, 'math': 3, 'english': 3}, {'name': '4', 'id': '4', 'chinese': 4, 'math': 4, 'english': 4}]
 

Finally, let's compare the difference between old and new:

student_old =

["{'name': '1', 'id': '1', 'chinese': '1', 'math': '1', 'english': '1'}\n",

"{'name': '2', 'id': '2', 'chinese': 2, 'math': 2, 'english': 2}\n",

"{'name': '3', 'id': '3', 'chinese': 3, 'math': 3, 'english': 3}\n",

"{'name': '4', 'id': '4', 'chinese': 4, 'math': 4, 'english': 4}\n"]


student_new=
[{'name': '1', 'id': '1', 'chinese': '1', 'math': '1', 'english': '1'},

{'name': '2', 'id': '2', 'chinese': 2, 'math': 2, 'english': 2},

{'name': '3', 'id': '3', 'chinese': 3, 'math': 3, 'english': 3},

{'name': '4', 'id': '4', 'chinese': 4, 'math': 4, 'english': 4}]

  It can be seen that the original student_old is in string format, which is not easy to sort; After a series of format conversion operations, the new student_new is

 =========================================================================

  Next, select 1. Descending or ascending? 2. With what grades?

 asc_or_desc = input('Please select (1).Ascending order | 2.(descending):')
    if asc_or_desc == '1':
        asc_or_desc_bool = False    #asc_ or_ Boolean value of desc.
    elif asc_or_desc == '2':
        asc_or_desc_bool = True
    else:
        print('Input error, please re-enter.')
        time.sleep(2)
        sort()

Note: we need to know the relationship between list.sort(reverse = Ture) and   The difference between list.sort(reverse = False)

Here are two pieces of code:

a = [2,3,77,45,0]
a.sort(reverse=False)
print(a)

#Output: [0, 2, 3, 45, 77]
a = [2,3,77,45,0]
a.sort(reverse=True)
print(a)

#Output: [77, 45, 3, 2, 0]

That is, Fales indicates ascending order and True indicates reverse order. So we need to define ASC first_ or_ The Boolean value of desc for subsequent sorting operations.

Next, choose what grades to sort with:

mode = input('Please select sorting method (1).grade scores of Chinese | 2.Mathematics achievement | 3.English achievement | 4.Total score):')  #Choose what grades to sort by.
    if mode == '1':
        student_new.sort(key = lambda student_new :int(student_new['chinese']),reverse = asc_or_desc_bool)
    elif mode == '2':
        student_new.sort(key = lambda student_new :int(student_new['math']),reverse = asc_or_desc_bool)
    elif mode == '3':
        student_new.sort(key = lambda student_new :int(student_new['english']),reverse = asc_or_desc_bool)
    elif mode == '4':
        student_new.sort(key = lambda student_new :int(student_new['chinese']) + int(student_new['math']) + int(student_new['english']),reverse = asc_or_desc_bool)
    else:
        print('Input error, please re-enter.')
        time.sleep(2)
        sort()
    show_student(student_new)

Pull out a single row:

student_new.sort(key = lambda student_new :int(student_new['chinese']),reverse = asc_or_desc_bool)

key = lambda: we need to use the parameter key, that is, keyword. Look at the following command. Lambda is an implicit function and a fixed writing method.

student_new :int(student_new['chinese']): student_new can write anything. You can write X: int (x['chinese ']) directly. Adding int() needs to change the string content to integer type (we need numbers). x['chinese '] refers to calling the Chinese score in the dictionary.

reverse = asc_or_desc_bool: it introduces the usage of reverse. This is equal to False or True.

Finally, call the show() function to display student_. new.

2, show() section

def show():
    student_lst = []
    if os.path.exists(filename):  # Does the. txt file exist
        with open(filename, 'r', encoding='UTF-8') as rfile:
            student = rfile.readlines()
        for item in student:
            student_lst.append(eval(item))        #Traverse the. txt file and write the contents of each line to the student_ In LST

        show_student(student_lst)                 #Write line by line. After all, show the students together_ lst
        print('After all information is displayed, you will return to the main menu.')
        time.sleep(2)

So far, the system has been completed. The complete code of this chapter is as follows:

def sort():
    if os.path.exists(filename):   #Determine whether a. txt file exists
        with open(filename,'r',encoding='UTF-8') as file:
            student_old= file.readlines()     #Put the contents of the file into the student_old
            #print('output student_old')
            #print(student_old)
        student_new = []
        for item in student_old:
            d = dict(eval(item))
            #print('output d ')
            #print(d)
            student_new.append(d)
            #print('output student_new')
            #print(student_new)
    else:
        return

    asc_or_desc = input('Please select (1).Ascending order | 2.(descending):')
    if asc_or_desc == '1':
        asc_or_desc_bool = False    #asc_ or_ Boolean value of desc.
    elif asc_or_desc == '2':
        asc_or_desc_bool = True
    else:
        print('Input error, please re-enter.')
        time.sleep(2)
        sort()
    mode = input('Please select sorting method (1).grade scores of Chinese | 2.Mathematics achievement | 3.English achievement | 4.Total score):')  #Choose what grades to sort by.
    if mode == '1':
        student_new.sort(key = lambda student_new :int(student_new['chinese']),reverse = asc_or_desc_bool)
    elif mode == '2':
        student_new.sort(key = lambda student_new :int(student_new['math']),reverse = asc_or_desc_bool)
    elif mode == '3':
        student_new.sort(key = lambda student_new :int(student_new['english']),reverse = asc_or_desc_bool)
    elif mode == '4':
        student_new.sort(key = lambda student_new :int(student_new['chinese']) + int(student_new['math']) + int(student_new['english']),reverse = asc_or_desc_bool)
    else:
        print('Input error, please re-enter.')
        time.sleep(2)
        sort()
    show_student(student_new)    #Displays the sorted results

    answer = str(input('Continue sorting? T/F: '))
    if answer == 'F':
        print('Exiting, please wait.')
        time.sleep(2)
        return
    elif answer == 'T':
        sort()
    else:
        print('Input error.')
        time.sleep(2)
        sort()

#Function (display) section
def show():
    student_lst = []
    if os.path.exists(filename):  # Does the. txt file exist
        with open(filename, 'r', encoding='UTF-8') as rfile:
            student = rfile.readlines()
        for item in student:
            student_lst.append(eval(item))        #Traverse the. txt file and write the contents of each line to the student_ In LST

        show_student(student_lst)                 #Write line by line. After all, show the students together_ lst
        print('After all information is displayed, you will return to the main menu.')
        time.sleep(2)

    else:
        print('No corresponding data found.')  # The. txt file does not exist
        time.sleep(2)
        menu()

(end)

Tags: Python Pycharm

Posted on Wed, 01 Sep 2021 21:58:31 -0400 by RadixDev