I'm trying to sort the list based on the class number using sort, but it doesn't sort and comes out in the order of the input value, what should I do?

Asked 2 years ago, Updated 2 years ago, 15 views

elif menu == 4:
    sorted_list = sorted(student_list, key=lambda hakbun:student.hakbun)
    print_student(sorted_list)

When this code is executed, sorted_list should be printed in the order of school year, but it will be printed in the order of input. I'd appreciate it if you could let me know if you know any solutions.

python

2022-09-21 10:21

2 Answers

I'll show you in detail so that you don't make mistakes like this

sorted_list = sorted(student_list, key=lambda hakbun:student.hakbun)
sorted_list = sorted(student_list, key=lambda student: student.hakbun) 

The above code was written by yourself and the second code was answered by someone else

If you're not sure, look at the next code

sorted(student_list, key=lambda hakbun:student.hakbun)
sorted(student_list, key=lambda student: student.hakbun) 

But if you're not sure, look at the next code

key=lambda hakbun:student.hakbun
key=lambda student: student.hakbun

I'm sure you'll know what's wrong with you if you've come this far.

If you've got a problem and you've found out where it happened, I hope you get into the habit of carefully examining what the problem is in that area.


2022-09-21 10:21

It's a situation where many people are frustrated. 🤣
Throw the code below and finish my turn:

class Student():
    def __init__(self, name, hakbun, major, kor, eng, math):
        self.name = name
        self.hakbun = hakbun
        self.kor = kor
        self.eng = eng
        self.math = math

def Insert_student(name, hakbun, major, kor, eng, math):
    student = Student(name,hakbun, major, kor, eng, math)
    return student

student_list = []
student = Insert_student ('Hey', '90198', 'Why', 100, 80, 90)
student_list.append(student)
student_list.append(Insert_student('ya2', '70101', 'why2', 100, 80, 90))
student_list.append(insert_student('ya3', '13146', 'why3', 100, 80, 90))
student_list.append(Insert_student('ya4', '40001', 'Why4', 100, 80, 90))

sorted_list = sorted(student_list, key=lambda student: student.hakbun)
unsorted_list = sorted(student_list, key=lambda hakbun: student.hakbun)

print('\nOriginal before sorting:')
for ele in student_list:
    print(ele.hakbun)

print ('\nAfter sorting:')
for ele in sorted_list:
    print(ele.hakbun)

print ('\nInvalid Alignment:')
for ele in unsorted_list:
    print(ele.hakbun)


2022-09-21 10:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.