Home > Software design >  How do I align/merge 2 lists? (Python)
How do I align/merge 2 lists? (Python)

Time:11-06

I really do not know how to describe this but I'll include an output in preformatted text after my horrific explanation. So... I create three lists I need to use two, 'employeeSold' and 'employeeName,' however I need to merge/align the two so I can make a ranking system on who's got the most, I figured out how to order from largest to most significant for employeeSold, but I am most unsure on how to link the correct Name to the correct value, I figured it needs to come before the ordering though, but I really do not know what to type and I've spent a handful of hours thinking about it.


Here is an example OUTPUT of what I want for this code:

Ranking:
John - 5
Laura - 4
BOJO -1

It has assigned each integer (employeeSold) to each string (employeeName) and then ordered the integers (employeeSold) inserted by the user from largest to most significant and then printed their names next to their integer.


Here is my code:

def employee():
  employeeName = input("What is Employee's name?: ")
  employeeID = input("What is Employee's ID?: ")
  employeeSold = int(input("How many houses employee sold?: "))
  nameList.append(employeeName)
  idList.append(employeeID)
  soldList.append(employeeSold)
  nextEmployee = input("Add another employee? Type Yes or No: ")
  if nextEmployee == "2":
    employee()
  else:
    print("Employee Names:")
    print(", ".join(nameList))
    print("Employee's ID: ")
    print(", ".join(idList))
    print("Employee Sold:")
    print( " Houses, ".join( repr(e) for e in soldList ), "Houses" )
    print("Commission: ")
    employeeCommission = [i * 500 for i in soldList]
    print(", ".join( repr(e) for e in employeeCommission ), "" )
    print("Commission Evaluation: ")
    totalCommission = sum(employeeCommission)
    print(totalCommission)
    soldList.sort(reverse=True)
    print("Employee Ranking: ")
    ranking = (", ".join( repr(e) for e in soldList))
    print(ranking)
nameList = []
idList = []
soldList = []

employee()```
--------
Any help would be very much so appreciated.

CodePudding user response:

You could consider breaking up your logic into multiple functions and sorting a zip of the names, and num_houses_sold list to print a ranking as you specified:

def get_int_input(prompt: str) -> int:
    num = -1
    while True:
        try:
            num = int(input(prompt))
            break
        except ValueError:
            print('Error: Enter an integer, try again...')
    return num

def get_yes_no_input(prompt: str) -> bool:
    allowed_responses = {'y', 'yes', 'n', 'no'}
    user_input = input(prompt).lower()
    while user_input not in allowed_responses:
        user_input = input(prompt).lower()
    return user_input[0] == 'y'

def get_single_employee_info(names: list[str], ids: list[int],
                             num_sold_houses: list[int]) -> None:
    names.append(input('What is the employee\'s name?: '))
    ids.append(get_int_input('What is the employee\'s id?: '))
    num_sold_houses.append(
        get_int_input('How many houses did the employee sell?: '))

def get_houses_sold_info(names: list[str], ids: list[int],
                         num_sold_houses: list[int]) -> None:
    get_single_employee_info(names, ids, num_sold_houses)
    add_another_employee = get_yes_no_input('Add another employee [yes/no]?: ')
    while add_another_employee:
        get_single_employee_info(names, ids, num_sold_houses)
        add_another_employee = get_yes_no_input(
            'Add another employee [yes/no]?: ')

def print_entered_info(names: list[str], ids: list[int],
                       num_sold_houses: list[int]) -> None:
    print()
    row_width = 12
    comission_per_house = 500
    header = ['Name', 'Id', 'Houses Sold', 'Commission']
    print(' '.join(f'{h:<{row_width}}' for h in header))
    commission = [n * comission_per_house for n in num_sold_houses]
    for values in zip(*[names, ids, num_sold_houses, commission]):
        print(' '.join(f'{v:<{row_width}}' for v in values))
    print()
    total_commission = sum(commission)
    print(f'Total Commission: {total_commission}')
    print()
    rankings = sorted(zip(num_sold_houses, names), reverse=True)
    print('Ranking:')
    for houses_sold, name in rankings:
        print(f'{name} - {houses_sold}')

def main() -> None:
    print('Houses Sold Tracker')
    print('===================')
    names, ids, num_houses_sold = [], [], []
    get_houses_sold_info(names, ids, num_houses_sold)
    print_entered_info(names, ids, num_houses_sold)

if __name__ == '__main__':
    main()

Example Usage:

Houses Sold Tracker
===================
What is the employee's name?: Laura
What is the employee's id?: 1
How many houses did the employee sell?: a
Error: Enter an integer, try again...
How many houses did the employee sell?: 4
Add another employee [yes/no]?: yes
What is the employee's name?: John
What is the employee's id?: 2
How many houses did the employee sell?: 5
Add another employee [yes/no]?: y
What is the employee's name?: BOJO
What is the employee's id?: 3
How many houses did the employee sell?: 1
Add another employee [yes/no]?: no

Name         Id           Houses Sold  Commission  
Laura        1            4            2000        
John         2            5            2500        
BOJO         3            1            500         

Total Commission: 5000

Ranking:
John - 5
Laura - 4
BOJO - 1

As an aside if you ever make something real don't use a sequential user id, the amount of information you can obtain from just monitoring this is insane, e.g., the rate of user acquisition, which you don't want external people to be able to figure out.

CodePudding user response:

You can use zip function to merge lists and then custom key sorting. SortByName function returning the sort key name and SortBySalary function returning key salary

def SortByName(FullList):
    return FullList[0]

def SortBySalary(FullList):
    return FullList[2]

NamesList=['John','Laura','Bojo']
IdList=[1,2,5]
SalaryList=[2000,1000,5000]

ZippedList=zip(NamesList,IdList,SalaryList)
print ZippedList

# result
#[('John', 1, 2000), ('Laura', 2, 1000), ('Bojo', 5, 5000)]

ZippedList.sort(key=SortByName,reverse=True)
print ZippedList

# result
# [('Laura', 2, 1000), ('John', 1, 2000), ('Bojo', 5, 5000)]

ZippedList.sort(key=SortBySalary,reverse=True)
print ZippedList

# result
# [('Bojo', 5, 5000), ('John', 1, 2000), ('Laura', 2, 1000)]

If you later want to sort the lists by id, just implement id sorting function.

def SortByID(FullList):
    return FullList[1]

ZippedList.sort(key=SortByID)
  • Related