Search code examples
classsortinglambda

Lambda Sorted won't sort


I'm trying create a lambda Sorted by age, but it's not sorting, would appreciate if someone spots the error. Thank you

I made a class and a menu to input employees with name and age, objective is to print the list sorted by age

Here I show the code I have so far

    class employee:
    def __init__(self, name, age):
        self.name = name
        self.age = age
i = 0
list = []
def show():
    k = 0
    while k < len(list):
        list2 =[
            {'Name': list[k].name,
             'Age' : list[k].age}]
        _sorted = sorted(list2, key=lambda x: x['Age'], reverse=True)
        print(_sorted)
        k += 1
while i == 0:
    print("Menu")
    print("1. Register")
    print("2. Show")
    print("3. Exit")
    option = int(input())
    if option == 1:
        print("Register")
        n = str(input("Ingrese el nombre del empleado: "))
        e = int(input("Ingrese la edad del empleado: "))
        emp = employee(n, e)
        list.append(emp)
        print("Empleado guardado con éxito!")

    elif option == 2:
        print("Mostrar")
        mostar()

    elif option == 3:
        exit()
    else:
        print("Option inválid")

Solution

  • I've made some minor changes to make the program run:

    class employee:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    
    def show(lst):         # <--- make function with parameter, don't use global values
        for emp in sorted(lst, key=lambda x: x.age, reverse=True):   # <--- iterate over sorted list 
            print(emp.name, emp.age)    # <-- print name, age
    
    
    lst = []
    
    while True:          # <-- you don't need `i` variable here, just break when you want to exit
        print("Menu")
        print("1. Register")
        print("2. Show")
        print("3. Exit")
        option = int(input())
        if option == 1:
            print("Register")
            n = str(input("Ingrese el nombre del empleado: "))
            e = int(input("Ingrese la edad del empleado: "))
            emp = employee(n, e)
            lst.append(emp)
            print("Empleado guardado con éxito!")
    
        elif option == 2:
            print("Mostrar")
            show(lst)                 # <--- use show(), not mostrar()
    
        elif option == 3:
            break                     # <--- to exit, break
        else:
            print("Option inválid")